package com.vw.mep.dms.service.maintation.svc.service.impl.SVC0101;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;

import com.vw.mep.common.mp.dto.DbUnionCommonDto;
import com.vw.mep.common.mp.pagination.QmPage;
import com.vw.mep.dms.api.common.dto.PDI.SaleCMPDI;
import com.vw.mep.dms.api.common.dto.PagePropertyDTO;
import com.vw.mep.dms.api.common.dto.SalCusCarPO;
import com.vw.mep.dms.api.common.dto.Svc0101_03.SVC0101_03DTO;
import com.vw.mep.dms.api.common.model.Message;
import com.vw.mep.dms.api.common.utils.DotNetToJavaStringHelper;
import com.vw.mep.dms.api.common.utils.LocalDateTimeUtils;
import com.vw.mep.dms.api.common.utils.RestResultResponseUtils;
import com.vw.mep.dms.framework.bean.dto.DMSLoginInfoDto;
import com.vw.mep.dms.framework.bean.dto.framework.RestResultResponse;
import com.vw.mep.dms.framework.config.thread.ExecutorManager;
import com.vw.mep.dms.framework.service.FWSystemOrderNoService;
import com.vw.mep.dms.framework.util.bean.ApplicationContextHelper;
import com.vw.mep.dms.function.StringUtils;
import com.vw.mep.dms.function.exception.DmsBizException;
import com.vw.mep.dms.service.common.entity.dto.*;
import com.vw.mep.dms.service.common.entity.po.*;
import com.vw.mep.dms.service.maintation.svc.entity.po.svcorderspa.SvcOrderSpaPO;
import com.vw.mep.dms.service.common.entity.vo.*;
import com.vw.mep.dms.service.common.mapper.*;
import com.vw.mep.dms.service.common.utils.TimeUtil;
import com.vw.mep.dms.service.maintation.app.dto.GuideRecordDto;
import com.vw.mep.dms.service.maintation.app.service.SvcAppService;
import com.vw.mep.dms.service.maintation.common.feign.IInvokeService;
import com.vw.mep.dms.service.maintation.common.service.PUCCommonService;
import com.vw.mep.dms.service.maintation.common.service.STMCommonService;
import com.vw.mep.dms.service.maintation.common.util.DBType;
import com.vw.mep.dms.service.maintation.crm.entity.dto.CRMInsuranceVODTO;
import com.vw.mep.dms.service.maintation.crm.entity.dto.crm0001.CRMSALGetVehicleInfoVODTO;
import com.vw.mep.dms.service.maintation.crm.entity.dto.crm0001.CRMVehicleQueryVoDTO;
import com.vw.mep.dms.service.maintation.crm.entity.dto.crm0001.STMDictSHVoDTO;
import com.vw.mep.dms.service.maintation.crm.entity.po.SvcOrderCusinfoPO;
import com.vw.mep.dms.service.maintation.crm.entity.po.VehiclePO;
import com.vw.mep.dms.service.maintation.crm.mapper.CRMVehicleQueryVOMapper;
import com.vw.mep.dms.service.maintation.crm.mapper.crm0001.Crm0001Mapper;
import com.vw.mep.dms.service.maintation.feign.client.*;
import com.vw.mep.dms.service.maintation.mda.entity.po.MdaProductMixPO;
import com.vw.mep.dms.service.maintation.stm.entity.po.UserRolePO;
import com.vw.mep.dms.service.maintation.svc.controller.RabbitMqUtils;
import com.vw.mep.dms.service.maintation.svc.domin.PadHomeCensus;
import com.vw.mep.dms.service.maintation.svc.entity.dto.SVCServiceRequestVODTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.*;
import com.vw.mep.dms.service.maintation.svc.entity.dto.pad0101.SVCPadProgressDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0101.*;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0101.svc0101_04.SVCFreeMTItfDataCM;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0201.Svc0201ParaTransformCMDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0203.*;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0204.Svc0204RescueBillDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0301.StlSettlementTypeSHViewDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0301.Svc0104SVCSettlementClubDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0307.SPAListDefineCMDTO;
import com.vw.mep.dms.service.maintation.svc.entity.dto.svc0401.SVC0401UserRoleDTO;
import com.vw.mep.dms.service.maintation.svc.entity.po.SvcBusConfigPO;
import com.vw.mep.dms.service.maintation.svc.entity.po.SvcEstimatePO;
import com.vw.mep.dms.service.maintation.svc.entity.po.SvcOrderPO;
import com.vw.mep.dms.service.maintation.svc.entity.po.*;
import com.vw.mep.dms.service.maintation.svc.entity.vo.SvcOrderQuestionVO;
import com.vw.mep.dms.service.maintation.svc.entity.vo.svc0101.SVCServiceRequestQueryParaCM;
import com.vw.mep.dms.service.maintation.svc.entity.vo.svc0101.*;
import com.vw.mep.dms.service.maintation.svc.entity.vo.svc0204.Svc0204RescueBillVO;
import com.vw.mep.dms.service.maintation.svc.mapper.*;
import com.vw.mep.dms.service.maintation.svc.mapper.pad0101.Pad0010Mapper;
import com.vw.mep.dms.service.maintation.svc.mapper.pad0101.SvcTakeCarViewMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.sany0007.Sany0007Mapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0101.Svc0101Mapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0104.SvcGetDisCountByItemCodeMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0203.SVCBookRegisterVOMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0203.SVCBookSPAVOMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0203.SVCBookSuitItemVOMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0203.SVCServiceCarUseInfoVOMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0301.StlSettlementTypeSHViewMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0401.Svc0104SvcOrderMapper;
import com.vw.mep.dms.service.maintation.svc.mapper.svc0401.Svc0401SvcOrderMapper;
import com.vw.mep.dms.service.maintation.svc.service.*;
import com.vw.mep.dms.service.maintation.svc.service.pagingservice.Svc0101FYService;
import com.vw.mep.dms.service.maintation.svc.task.BookOrderInfoToSanyAppTask;
import com.vw.mep.dms.service.maintation.svc.task.OrderInfoToEwsTask;
import com.vw.mep.dms.service.maintation.svc.task.UploadOrderDataTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class Svc0101ServiceImpl implements Svc0101Service {

    @Autowired
    Svc0101Mapper svc0101Mapper;
    @Autowired
    Svc0203Service svc0203Service;
    @Autowired
    SvcToCrmService svcToCrmService;

    @Autowired
    ElsaProService elsaProService;
    @Autowired
    SvcServiceRequestViewMapper svcServiceRequestViewMapper;

    @Autowired
    Crm0001Mapper crm0001Mapper;

    @Autowired
    CRMInsuranceVOMapper cRMInsuranceVOMapper;

    @Autowired
    Svc0104SvcOrderMapper svc0104SvcOrderMapper;

    @Autowired
    SVCServiceRequestSpaDTOMapper svcServiceRequestSpaDTOMapper;

    @Autowired
    SVCItemKindSHVOMapper sVCItemKindSHVOMapper;

    @Autowired
    private IInvokeService iInvokeService;

    @Autowired
    STMCommonService stmCommonService;

    @Autowired
    CRMGetVehicleVOMapper cRMGetVehicleVOMapper;

    @Autowired
    Svc0101_04Service svc0101_04Service;

    @Autowired
    Message message;

    @Autowired
    SVCMaintainSuitItemDTOMapper sVCMaintainSuitItemDTOMapper;

    @Autowired
    private FWSystemOrderNoService fwSystemOrderNoService;

    @Autowired
    SvcRecallCusMapper svcRecallCusMapper;

    @Autowired
    private SVCBusConfigMapper sVCBusConfigMapper;

    @Autowired
    PUCCommonService pUCCommonService;

    @Autowired
    CRMVehicleQueryVOMapper cRMVehicleQueryVOMapper;

    @Autowired
    private StlSettlementTypeSHViewMapper stlSettlementTypeSHViewMapper;

    @Autowired
    SVCMaintainSuitViewMapper sVCMaintainSuitViewMapper;

    @Autowired
    private SVCGetSVCSugeestMitPRMapper sVCGetSVCSugeestMitPRMapper;

    @Autowired
    SPAMasterDataAllMapper spaMasterDataAll;

    @Autowired
    private SPTAddToolVOMapper sPTAddToolVOMapper;

    @Autowired
    private SvcToCdpService svcToCdpService;

    @Autowired
    PUCCommonService pucCommonService;

    @Autowired
    private SVCBookRegisterVOMapper sVCBookRegisterVOMapper;

    @Autowired
    Svc0201SvcEstimateMapper svc0201SvcEstimateMapper;

    @Autowired
    private SalFeignClient ssalFeignClient;

    @Autowired
    ClmVa6UnCompensationMapper clmb38;

    @Autowired
    private SpaGetDrawDetailForSvcVOMapper spaGetDrawDetailForSvcVOMapper;

    @Autowired
    private SVCBookSuitItemVOMapper sVCBookSuitItemVOMapper;

    @Autowired
    private SVCBookSPAVOMapper sVCBookSPAVOMapper;

    @Autowired
    private STMPersonQASHVOMapper sTMPersonQASHVOMapper;

    @Autowired
    SvcEstimateItemsMapper svcEstimateItemsMapper;

    @Autowired
    SVCEstimateToolVOMapper sVCEstimateToolVOMapper;

    @Autowired
    SVCServiceRequestQAVOMapper sVCServiceRequestQAVOMapper;

    @Autowired
    Svc0401SvcOrderMapper svc0401SvcOrderMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private SvcToCusAppService svcToCusAppService;

    @Autowired
    private SVCServiceCarUseInfoVOMapper svcServiceCarUseInfoVOMapper;

    @Autowired
    private ArchivesFeignClient archivesFeignClient;

    @Autowired
    private SvcGetDisCountByItemCodeMapper svcGetDisCountByItemCodeMapper;

    @Autowired
    private Svc0101_AllarchivesService svc0101_allarchivesService;

    @Autowired
    private Svc0204Service svc0204Service;

    @Autowired
    private Svc0101FYService svc0101FYService;

    @Autowired
    private SvcAppService svcAppService;

    @Autowired
    private SvcTakeCarViewMapper svcTakeCarViewMapper;

    @Autowired
    private RetailFeignClient retailFeignClient;

    @Autowired
    Pad0101Service pad0101Service;
    @Autowired
    Pad0010Mapper pad0010Mapper;

    @Autowired
    SpaFeignClient spaFeignClient;

    @Autowired
    SvcToSanyCrmService svcToSanyCrmService;

    @Autowired
    SvcToSanyAppService svcToSanyAppService;

    @Autowired
    Sany0007Mapper sany0007Mapper;

    @Resource
    SvcToSanyCrmMapper svcToSanyCrmMapper;


    @Value("${mybatis-plus.configuration.variables.vCusGroupId}")
    private String vCusGroupId;

    private static final Logger logger = LoggerFactory.getLogger(Svc0101ServiceImpl.class);

    @Override
    public Map<String, Object> traninit() {

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SVCServiceRequestQueryParaCM sVCServiceRequestQueryParaCM = new SVCServiceRequestQueryParaCM();
        SVCParaTransformCM sVCParaTransformCM = new SVCParaTransformCM();

        java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dEnd = format1.format(new Date());
        List<String> date = new ArrayList<>();
        date.add(0, "1900-01-01 00:00:00");
        date.add(1, dEnd);
        sVCServiceRequestQueryParaCM.setdEnter(date);
        sVCServiceRequestQueryParaCM.setcRepairing(1);
        sVCServiceRequestQueryParaCM.setvDateType("01");
        sVCServiceRequestQueryParaCM.setKeyWord("");
        sVCParaTransformCM.setnCusGroupID("D49F66C6-52A2-4D87-B5DC-C0698E2A8E74");
        Map<String, Object> map = new HashMap<>();
        map.put("sVCServiceRequestQueryParaCM", sVCServiceRequestQueryParaCM);
        map.put("sVCParaTransformCM", sVCParaTransformCM);
        String takeCarService =
                stmCommonService.GetParameters("TakeCarService", userInfor.getnBID(), "SVC");
        map.put("takeCarService", takeCarService);

        return map;
    }

    @Override
    public SVC0101FYVO search(SVCServiceRequestQueryParaVO sVCServiceRequestQueryParaVO) {


        SVC0101FYVO page = dosearch(sVCServiceRequestQueryParaVO);

        return page;
    }


    private SVC0101FYVO dosearch(SVCServiceRequestQueryParaVO sVCServiceRequestQueryParaVO) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SVC0101FYVO result = new SVC0101FYVO();
        SVCServiceRequestQueryParaCM sVCServiceRequestQueryParaCM = sVCServiceRequestQueryParaVO.getsVCServiceRequestQueryParaCM();

        int cRepairing = sVCServiceRequestQueryParaCM.getcRepairing();
        String vDateType = sVCServiceRequestQueryParaCM.getvDateType();
        int cConsultant = sVCServiceRequestQueryParaCM.getcConsultant();
        String keyWord = sVCServiceRequestQueryParaCM.getKeyWord();
        String JCTQSJ = stmCommonService.GetParameters("JCTQSJ", userInfor.getnDID(), "SVC");
        DbUnionCommonDto query = new DbUnionCommonDto();
        query.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        query.setQueryConditions("a.nbid", 0, userInfor.getnBID());
        if (cRepairing == 1) {
            query.setQueryConditions("a.vRepairStatus", 0, "00");
        }
        //进场日期
        if (StringUtils.isNullOrEmpty(sVCServiceRequestQueryParaCM.getDateFlag())) {
            if (sVCServiceRequestQueryParaCM.getdEnter() != null && sVCServiceRequestQueryParaCM.getdEnter().size() == 2) {
                String dBegin = sVCServiceRequestQueryParaCM.getdEnter().get(0);
                String dEnd = sVCServiceRequestQueryParaCM.getdEnter().get(1);
                TimeUtil.checkDaySection(dBegin, dEnd);
                query.setQueryConditions("a.denter between '" + dBegin + "' and  '" + dEnd + "' ", 14, "");
            }
        }
        query.setQueryConditions("IFNULL(a.cDelete,'0')", 0, "0");
        query.setQueryConditions("( ( c06.VSYSTEMCLSPROP <> 'PDI'  AND c06.VSYSTEMCLSPROP IS NOT NULL) OR ( c06.VSYSTEMCLSPROP IS NULL AND a.VSVCKIND <> '8')) ", 10, "");
        query.setQueryConditions("IFNULL(a.cPDIS,'0') ", 0, "0");
//        query.setQueryConditions("a.vsvckind ", 9, "8,P,J");
        if (!StringUtils.isNullOrEmpty(keyWord)) {
            query.setQueryConditions(" ( a.VBillNO LIKE '%" + keyWord + "%' or  a.vvin LIKE  '%" + keyWord + "%' or   a.VLicenseTag LIKE '%" + keyWord + "%'   or  r.vCusName like  '%" + keyWord + "%' ) ", 14, "");
        }

        if (1 == cConsultant) {
            query.setQueryConditions("a.nSVCAdviserID ", 0, userInfor.getiD());
        }

        // 微信端增加检索条件  mxy   2021-10-26  start
        String keyWordFromRMS = sVCServiceRequestQueryParaCM.getKeyWordFromRMS();
        if (!StringUtils.isNullOrEmpty(keyWordFromRMS)) {
            if (StringUtils.isNullOrEmpty(sVCServiceRequestQueryParaCM.getDateFlag())) {
                query.setQueryConditions(" ( a.VBillNO LIKE  '%" + keyWordFromRMS + "%' or  a.vvin LIKE  '%" + keyWordFromRMS + "%' or r.vCusMobile LIKE '%" + keyWordFromRMS + "%'   or  r.vCusName like  '%" + keyWordFromRMS + "%' ) ", 14, "");
            } else {
                query.setQueryConditions("a.vvin", 0, keyWordFromRMS);
            }
        }

        if (sVCServiceRequestQueryParaCM.getvRepairStatusList() != null && !sVCServiceRequestQueryParaCM.getvRepairStatusList().isEmpty()) {
            query.setQueryConditions("a.vRepairStatus", 8, sVCServiceRequestQueryParaCM.getvRepairStatusList());
        }

        if (sVCServiceRequestQueryParaCM.getvSvcKindList() != null && !sVCServiceRequestQueryParaCM.getvSvcKindList().isEmpty()) {
            query.setQueryConditions("a.vSvcKind", 8, sVCServiceRequestQueryParaCM.getvSvcKindList());
        }

        // 微信端增加检索条件  mxy   2021-10-26  end
        sVCServiceRequestQueryParaVO.setSize(sVCServiceRequestQueryParaVO.getPageSize());
        sVCServiceRequestQueryParaVO.setCurrent(sVCServiceRequestQueryParaVO.getCurrentPage());
        QmPage<SVCGetServiceRequest> list_table = null;
        //判断是否使用合计功能
        Map<String, Object> para = new HashMap<String, Object>();
        para.put("JCTQSJ", JCTQSJ);
        int usedHJ = sVCServiceRequestQueryParaVO.getUsedJH();
        list_table = svc0101FYService.getHjPage(sVCServiceRequestQueryParaVO, result, query, para, usedHJ);

        result.setTableData(list_table);
        return result;
    }

    //老分页存储过程，改造新分页
    private Page<SVCGetServiceRequest> dosearch1(
            String dBegin,
            String dEnd,
            int cRepairing,
            String vDateType,
            int cConsultant,
            String keyWord,
            int currentPage,
            int pageSize) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SVCGetServiceRequestVO addVo = new SVCGetServiceRequestVO();
        addVo.setNdid(userInfor.getnDID());
        addVo.setNbid(userInfor.getnBID());
        addVo.setdBeging(dBegin);
        addVo.setdEnd(dEnd);
        addVo.setcRepairing(cRepairing + "");
        addVo.setnUserID(userInfor.getiD());
        addVo.setvBillNO("");
        addVo.setvDateType(vDateType);
        addVo.setcConsultant(cConsultant + "");
        addVo.setKeyWord(keyWord);
        Page<SVCGetServiceRequest> page = new Page<>();

        List<?> result = svc0101Mapper.GetServiceRequestList(addVo, currentPage, pageSize);
        List<SVCGetServiceRequest> list = (List<SVCGetServiceRequest>) result.get(0);
        List<PagePropertyDTO> pageProperty = (List<PagePropertyDTO>) result.get(1);

        int total = pageProperty.get(0).getTotal();
        page.setTotal(total);
        page.setRecords(list);
        return page;
    }


    // 编辑方法
    @Override
    public Map<String, Object> edit(@RequestBody SVCGetServiceRequest sVCGetServiceRequest) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        // FD 上传状态
        String DTSSstutes = "0";
        // 创建返回Map
        Map<String, Object> returnMap = new HashMap<>();
        // 初始化界面数据字典
        Map<String, Object> Dict = SetEnterDict(userInfor.getnDID());
        returnMap.put("dict", Dict);
        if (!StringUtils.isNullOrEmpty(sVCGetServiceRequest.getiD())) {
            DbUnionCommonDto SVCVO = new DbUnionCommonDto();
            SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            SVCVO.setQueryConditions("a.iD", 0, sVCGetServiceRequest.getiD());
            List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);


            // 获取到了委托书信息
            if (list.size() > 0) {
                // 增加预约标识
                if ("0".equals(list.get(0).getvSvcFrom())) {
                    returnMap.put("isBook", "1");
                } else if ("1".equals(list.get(0).getvSvcFrom())) {
                    SvcEstimatePO svcEstimatePO = new SvcEstimatePO();
                    svcEstimatePO.setiD(list.get(0).getnSvcFromBillID());
                    svcEstimatePO = svcEstimatePO.selectById();
                    if (svcEstimatePO != null && ("1").equals(svcEstimatePO.getvSvcFrom())) {
                        returnMap.put("isBook", "1");
                    }
                }
                // 获取车辆信息
                DbUnionCommonDto getVehicleInfoVO = new DbUnionCommonDto();
                getVehicleInfoVO.setQueryConditions("a.ndid", 0, list.get(0).getnDID());
                getVehicleInfoVO.setQueryConditions("a.vvin", 0, list.get(0).getvVin());
                List<CRMSALGetVehicleInfoVODTO> vehInfoList =
                        crm0001Mapper.sALGetVehicleInfoVO(getVehicleInfoVO);
                if (vehInfoList.size() > 0) {
                    list.get(0).setdProd(vehInfoList.get(0).getdProd());
                    list.get(0).setcOwnSell(vehInfoList.get(0).getcOwnSell());
                }
                // 查询客户档案填充省市区县 和客户详细地址
                // 增加省市区县list
                CustomerPO customerPO = new CustomerPO();
                QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("vCus", list.get(0).getvCus());
                queryWrapper.eq("ndid", userInfor.getnDID());
                List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
                if (cuslistPO != null && cuslistPO.size() > 0) {
                    customerPO = cuslistPO.get(0);
                    List<STMCityVODTO> vCityLinklist = new ArrayList<>();
                    vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
                    list.get(0).setvCityLink(vCityLinklist);
                    list.get(0).setvCusAddrDetail(customerPO.getvCusAddrDetail());
                    list.get(0).setnCityID(customerPO.getnCityID());

                    CustomerPO customerPO1 = cuslistPO.get(0);
                    String vAddrStr = customerPO1.getvProvince() + "," + customerPO1.getvCity();
                    if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(customerPO1.getvArea())){
                        vAddrStr = vAddrStr + "," + customerPO1.getvArea();
                    }
                    list.get(0).setvAddrSre(vAddrStr);
                }
                String useSanyCrm = stmCommonService.GetParameters("useSanyCrm", userInfor.getnDID(), "SVC");
                if (("1").equals(useSanyCrm)){
                    if (("01").equals(list.get(0).getvOrderType())){
                        if (!StringUtils.isNullOrEmpty(list.get(0).getvObjectID())){
                            Map serviceOrder = this.viewServiceOrderDetails(list.get(0).getvObjectID());
                            List<SvcOrderSpaPO> serviceSpas = (List<SvcOrderSpaPO>) serviceOrder.get("spalists");
                            this.updateSpaByCrmServiceOrder(list.get(0).getiD(),serviceSpas);
                        }
                    }
                    else if (("02").equals(list.get(0).getvOrderType())){
                        //如果类型是销售订单，那么调取CRM销售订单详情接口，如果有变化，更新预估配件
                        String[] crmOrderNos = list.get(0).getvObjectID().split(";");
                        logger.info("-------------------编号-----------------------------");
                        logger.info(crmOrderNos.toString());
                        //调crm拉取数据
                        Map saleOrder = this.viewSaleOrderDetails(crmOrderNos[1]);
                        list.get(0).setvZXYX(saleOrder.get("pmnttrms") == null ? "":saleOrder.get("pmnttrms").toString());
                        List<SvcOrderSpaPO> saleSpas = (List<SvcOrderSpaPO>) saleOrder.get("spalists");
                        String zzlgorth = saleOrder.get("zzlgorth") == null ? "":saleOrder.get("zzlgorth").toString();
                        this.updateSpaByCrmSaleOrder(list.get(0).getiD(),zzlgorth,saleSpas);
                    }
                }


                returnMap.put("sVCServiceRequestVO", list.get(0));
                // CRMInsuranceVO 保险
                List<CRMInsuranceVODTO> CRMInsuranceList =
                        getCRMInsuranceVO(list.get(0).getnDID(), list.get(0).getvVin());
                returnMap.put("cRMInsuranceVO", CRMInsuranceList);

                // 获取维修项目
                List<SVCServiceRequestItemVODTO> itemList = SelfGetItemByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestItemVO", itemList);

                // 获取预估备件
                List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestSpaVO", spaList);

                // 建议维修项目
                List<SVCServiceRequestSugeestMitVO> SelfGetSugItemByMainID =
                        svc0101_04Service.SelfGetSugItemByMainID(list.get(0).getiD(), "", 0);
                returnMap.put("sVCServiceRequestSugeestMitVO", SelfGetSugItemByMainID);

                // 获取专用工具
                List<SVCServiceRequestToolVO> toolList = SelfGetToolByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestToolVO", toolList);

                // 获取项目性质列表  去掉尊享悦享
                List<SVCItemKindSHVO> ItemKindlist =
                        GetItemKindList(
                                list.get(0).getvSvcKind(),
                                "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                                list.get(0).getcFreeMaintain() + "",
                                list.get(0).getcExtraMaintain() + "");

                returnMap.put("sVCItemKindSHVO", ItemKindlist);

                // 结算
                DbUnionCommonDto sVCSettlementView = new DbUnionCommonDto();
                sVCSettlementView.setQueryConditions("a.NCorID", 0, list.get(0).getiD());
                sVCSettlementView.setQueryConditions("a.CCancel", 0, "1");
                sVCSettlementView.setQueryConditions("a.ndid", 0, userInfor.getnDID());
                List<Svc0104SVCSettlementClubDTO> sVCSettlementList =
                        svc0104SvcOrderMapper.sVCSettlementVO(sVCSettlementView);

                if (sVCSettlementList != null && sVCSettlementList.size() > 0) {
                    returnMap.put("isCancelSettle", "1");
                } else {
                    returnMap.put("isCancelSettle", "0");
                }

                String padnstdID = list.get(0).getnStdID();
                //获取工时定额给pad
                if (StringUtils.isNullOrEmpty(padnstdID)) {

                    // 获取默认工时定额
                    GetStdDTO serviceResult = pucCommonService.GetStdBySaleTypeID(list.get(0).getnSaleTypeID());
                    String stdId = serviceResult.getnStdID();
                    if (!StringUtils.isNullOrEmpty(stdId)) {
                        padnstdID = stdId;
                    }

                }
                if (!StringUtils.isNullOrEmpty(padnstdID)) {
                    SvcStandardrationPO SVCStandardration = new SvcStandardrationPO();
                    SVCStandardration = getnstdID(list.get(0).getnStdID());
                    returnMap.put("pADnstd", SVCStandardration);
                }

            }
            ClmFdbillPO clmpo = new ClmFdbillPO();
            QueryWrapper<ClmFdbillPO> clmqueryWrapper = new QueryWrapper<>();
            clmqueryWrapper.eq("NSvcBillID", sVCGetServiceRequest.getiD());
            clmqueryWrapper.eq("CNew", "1");
            clmqueryWrapper.eq("CDelete", "0");
            List<ClmFdbillPO> clmlist = clmpo.selectList(clmqueryWrapper);
            if (clmlist != null && clmlist.size() > 0) {
                DTSSstutes = "1";
            } else {
                DTSSstutes = "0";
            }

        } else {
            returnMap.put("sVCServiceRequestVO", sVCGetServiceRequest);
        }

        // 删除维修项目权限 前端判断

        CheckUserRightVO vo = new CheckUserRightVO();
        vo.setNdid(userInfor.getnDID());
        vo.setUserID(userInfor.getiD());
        vo.setvRight("DeleteSvcItem");
        Map<String, Object> str = iInvokeService.checkuserright(userInfor.getnDID(), vo);
        Map<String, String> map = (Map<String, String>) str.get("data");
        Integer returnData = Integer.parseInt(map.get("isEXCE"));
        if (returnData == 0) {
            returnMap.put("deleteSvcItem", "0");
        } else {
            returnMap.put("deleteSvcItem", "1");
        }
        // 必须输入首保卡号 取数据字典
        String MustInputFirstMtNO =
                stmCommonService.GetParameters("MustInputFirstMtNO", userInfor.getnDID(), "SVC"); // 首保卡号参数
        returnMap.put("mustInputFirstMtNO", MustInputFirstMtNO);

        // 工时和工时费 允许负数
        String isAllowed = stmCommonService.GetParameters("IsAllowMinus", userInfor.getnBID(), "SVC");
        returnMap.put("isAllowed", isAllowed);

        // DTSS 未上传 不允许打印
//        String LFDSCJSL = stmCommonService.GetParameters("LFDSCJSL", userInfor.getnBID(), "SVC");
        returnMap.put("lFDSCJSL", "0");

        returnMap.put("dTSSstutes", DTSSstutes);
        // 取得取送车服务
        String takeCarService =
                stmCommonService.GetParameters("TakeCarService", userInfor.getnBID(), "SVC");
        returnMap.put("takeCarService", takeCarService);

        //进厂处理自动打印召回书
        /**************panghai 20210621 此参数隐藏，默认0************************************/
//        String LDYZHS =
//                stmCommonService.GetParameters("LDYZHS", userInfor.getnBID(), "SVC");
        returnMap.put("lDYZHS", "0");
        /**************panghai 20210621 此参数隐藏，默认0************************************/

        // 原厂仓库
        SpaWareHouseBePO spaWareHouseBePO = new SpaWareHouseBePO();
        QueryWrapper<SpaWareHouseBePO> spaWareHouseBePOQueryWrapper = new QueryWrapper<>();
        spaWareHouseBePOQueryWrapper.eq("ndid",userInfor.getnDID());
        spaWareHouseBePOQueryWrapper.eq("cMfr","1");
        spaWareHouseBePOQueryWrapper.eq("vWHType","SPA");
        spaWareHouseBePOQueryWrapper.ne("cstop","1");
        List<SpaWareHouseBePO> wareHouseBePOList = spaWareHouseBePO.selectList(spaWareHouseBePOQueryWrapper);
        if(!wareHouseBePOList.isEmpty()){
            List<Map<String,String>> vWHList = new ArrayList<>();
            for (SpaWareHouseBePO item:wareHouseBePOList
                 ) {
                Map<String,String> mapWH = new HashMap<>();
                mapWH.put("value",item.getvWH());
                mapWH.put("text",item.getvWHName());
                vWHList.add(mapWH);
            }
            returnMap.put("vWHList", vWHList);
        }



        return returnMap;
    }

    // 增加工时定额给PAD
    private SvcStandardrationPO getnstdID(String nStdID) {
        SvcStandardrationPO SVCStandardration = new SvcStandardrationPO();
        SVCStandardration = SVCStandardration.selectById(nStdID);
        return SVCStandardration;
    }

    // svc0101 保存前检查 获取校验里程数据
    @Override
    public MileageCheckDataDTO getmileagecheckdata(SVCServiceRequestVO sVCServiceRequestVO) {

        // 返回的数据模型
        MileageCheckDataDTO mileageCheckDataDTO = new MileageCheckDataDTO();
        // 获取委托书
        SVCServiceRequestVO SVCServiceRequestVO = sVCServiceRequestVO;
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        String vStdDayMileage =
                stmCommonService.GetParameters("StdDayMileage", userInfor.getnDID(), "SVC");
        BigDecimal nStdDayMileage = BigDecimal.ZERO;
        if (!StringUtils.isNullOrEmpty(vStdDayMileage)) {
            nStdDayMileage = new BigDecimal(vStdDayMileage);
        }

        // 获取车辆档案，获得档案里程，上次里程和上次维修时间

        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("a.NDID", 0, userInfor.getnDID());
        dbUnionCommonDto.setQueryConditions("a.VVin", 0, sVCServiceRequestVO.getvVin());
        List<CRMGetVehicleVODTO> vinList = cRMGetVehicleVOMapper.queryVin(dbUnionCommonDto);

        BigDecimal nMileage = BigDecimal.ZERO;
        BigDecimal nLastMileage = BigDecimal.ZERO;
        BigDecimal nThisMileage = SVCServiceRequestVO.getnMileage();
        LocalDateTime dLastRepair = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        LocalDateTime dEnter = SVCServiceRequestVO.getdEnter();
        // 日均行驶里程
        BigDecimal nDayMileage = BigDecimal.ZERO;

        // 判断 如果车辆信息取到了
        if ((!vinList.isEmpty()) && vinList.size() > 0) {
            nMileage = vinList.get(0).getnMileage();
            nLastMileage = vinList.get(0).getnLastMileage();
            if (nMileage == null) {
                nMileage = BigDecimal.ZERO;
            }
            if (nLastMileage == null) {
                nLastMileage = BigDecimal.ZERO;
            }
            // 如果没有上次维修日期，则使用购车日期
            if (vinList.get(0).getdLastRepair() == null
                    || LocalDateTime.of(1900, 1, 1, 0, 0, 0).equals(vinList.get(0).getdLastRepair())) {
                dLastRepair = vinList.get(0).getdBuy();
            } else {
                dLastRepair = vinList.get(0).getdLastRepair();
            }
            if (dLastRepair == null) {
                dLastRepair = sVCServiceRequestVO.getdBuy();
            }

            if (dLastRepair == null) {
//                dLastRepair = sVCServiceRequestVO.getdBuy();
                dLastRepair = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
            }
            // 里程差
            BigDecimal nDiffMileage = BigDecimal.ZERO;
            if (nThisMileage.compareTo(nLastMileage) > 0) {
                nDiffMileage = nThisMileage.subtract(nLastMileage);
            }
            // 日期差
            int daysNum = Period.between(dEnter.toLocalDate(), dLastRepair.toLocalDate()).getDays();
            BigDecimal nDiffDays = new BigDecimal(daysNum);

            if (nDiffDays.compareTo(BigDecimal.ZERO) > 0) {
                nDayMileage = nDiffMileage.divide(nDiffDays, 2, BigDecimal.ROUND_UP);
            }
        }
        mileageCheckDataDTO.setStdDayMileage(nStdDayMileage + "");
        mileageCheckDataDTO.setDayMileage(nDayMileage + "");
        mileageCheckDataDTO.setnMileage(nMileage + "");
        mileageCheckDataDTO.setnLastMileage(nLastMileage + "");
        String repair = LocalDateTimeUtils.localDateTimeToString(dLastRepair, "yyyy-MM-dd");
        mileageCheckDataDTO.setdLastRepair(repair);
        return mileageCheckDataDTO;
    }

    public Map<String, Object> SetEnterDict(String ndid) {
        Map<String, Object> map = new HashMap<>();
        // 客户类别
        List<STMDictSHVoDTO> CUSCLASS = crm0001Mapper.sTMDictSHVO(ndid, "CUSCLASS", vCusGroupId);
        map.put("cUSCLASS", CUSCLASS);
        // 业务类型
        List<STMDictSHVoDTO> SVCBizType = crm0001Mapper.sTMDictSHVO(ndid, "SVCBizType", vCusGroupId);
        map.put("sVCBizType", SVCBizType);
        // 评价类别
        List<STMDictSHVoDTO> CusEvaClass = crm0001Mapper.sTMDictSHVO(ndid, "CusEvaClass", vCusGroupId);
        map.put("cusEvaClass", CusEvaClass);
        // 洗车方式
        List<STMDictSHVoDTO> CarWashType = crm0001Mapper.sTMDictSHVO(ndid, "CarWashType", vCusGroupId);
        map.put("carWashType", CarWashType);
        // 保险公司
        List<STMDictSHVoDTO> INSURECOM = crm0001Mapper.sTMDictSHVO(ndid, "INSURECOM", vCusGroupId);
        map.put("iNSURECOM", INSURECOM);
        // 方便联系时间
        List<STMDictSHVoDTO> CONTACTTIME = crm0001Mapper.sTMDictSHVO(ndid, "CONTACTTIME", vCusGroupId);
        map.put("cONTACTTIME", CONTACTTIME);
        // 希望联系方式
        List<STMDictSHVoDTO> CONTACTTYPE = crm0001Mapper.sTMDictSHVO(ndid, "CONTACTTYPE", vCusGroupId);
        map.put("cONTACTTYPE", CONTACTTYPE);
        // 车辆类别
        List<STMDictSHVoDTO> CarType = crm0001Mapper.sTMDictSHVO(ndid, "CarType", vCusGroupId);
        map.put("carType", CarType);

        return map;
    }

    @Override
    public List<SVCServiceRequestItemVODTO> SelfGetItemByMainID(String NMainID) {

        DbUnionCommonDto view = new DbUnionCommonDto();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        view.setQueryConditions("a.NMainID", 0, NMainID);
        List<SVCServiceRequestItemVODTO> sVCServiceRequestItemList =
                svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfor.getnDID(), view, vCusGroupId);
        return sVCServiceRequestItemList;
    }

    @Override
    public List<SVCServiceRequestSpaDTO> SelfGetSPAByMainID(String NMainID) {
        DbUnionCommonDto preSPAView = new DbUnionCommonDto();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        preSPAView.setQueryConditions("a.NMainID", 0, NMainID);
        preSPAView.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        List<SVCServiceRequestSpaDTO> preSPAList =
                svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(preSPAView);
        return preSPAList;
    }

    @Override
    public List<SVCServiceRequestToolVO> SelfGetToolByMainID(String NMainID) {
        DbUnionCommonDto view = new DbUnionCommonDto();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        view.setQueryConditions("a.NMainID", 0, NMainID);
        view.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        List<SVCServiceRequestToolVO> SPT0103SVCServiceRequestToolList =
                svc0101Mapper.SVCServiceRequestToolVO(view);

        return SPT0103SVCServiceRequestToolList;
    }

    //  刷新维修项目列表
    @Override
    public Map<String, Object> resetitemlist(SvcServiceRequestViewDTO svcServiceRequestVO) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequestVO = svcServiceRequestVO;
        /*******************************20210520 逄海 添加id为空的校验***************************************/
        if(StringUtils.isNullOrEmpty(SVCServiceRequestVO.getiD())){
            message.putMessage("SVCMessage","125",new String[]{"未找到对应委托书，请关闭页面重新操作"});
        }
        /*******************************20210520 逄海 添加id为空的校验***************************************/
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getiD());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        if (list != null && list.size() > 0) {
            SVCServiceRequestVO = list.get(0);
            // 查询客户档案填充省市区县 和客户详细地址
            // 增加省市区县list
            CustomerPO customerPO = new CustomerPO();
            QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("vCus", list.get(0).getvCus());
            queryWrapper.eq("ndid", userInfor.getnDID());
            List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
            if (cuslistPO != null && cuslistPO.size() > 0) {
                customerPO = cuslistPO.get(0);
                List<STMCityVODTO> vCityLinklist = new ArrayList<>();
                vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
                list.get(0).setvCityLink(vCityLinklist);
                list.get(0).setvCusAddrDetail(customerPO.getvCusAddrDetail());
                String vAddrStr = customerPO.getvProvince() + "," + customerPO.getvCity() ;
                        if(!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(customerPO.getvArea())){
                            vAddrStr = vAddrStr    + "," + customerPO.getvArea();
                        }
                list.get(0).setvAddrSre(vAddrStr);
            }
        }

        // 获取维修项目
        List<SVCServiceRequestItemVODTO> ItemList = SelfGetItemByMainID(SVCServiceRequestVO.getiD());
        // 获取预估备件
        List<SVCServiceRequestSpaDTO> SpaList = SelfGetSPAByMainID(SVCServiceRequestVO.getiD());
        // 获取专用工具
        List<SVCServiceRequestToolVO> SptList = SelfGetToolByMainID(SVCServiceRequestVO.getiD());
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        map.put("sVCServiceRequestItemVO", ItemList);
        map.put("sVCServiceRequestSpaVO", SpaList);
        map.put("sVCServiceRequestToolVO", SptList);
        // 获取项目性质列表
        List<SVCItemKindSHVO> ItemKindlist =
                GetItemKindList(
                        SVCServiceRequestVO.getvSvcKind(),
                        "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                        SVCServiceRequestVO.getcFreeMaintain() + "",
                        SVCServiceRequestVO.getcExtraMaintain() + "");
        map.put("sVCItemKindSHVO", ItemKindlist);
        return map;
    }

    @Override
    public List<SVCItemKindSHVO> GetItemKindList(
            String vSvcKind, String nCustGroupId, String cFreeMaintain, String cExtraMaintain) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto ItemKindview = new DbUnionCommonDto();
        ItemKindview.setQueryConditions("a.NCusGroupID", 0, nCustGroupId);
        ItemKindview.setQueryConditions("a.VSvcCls", 0, vSvcKind);

        List<SVCItemKindSHVO> ItemKindlist = sVCItemKindSHVOMapper.getSVCItemKindSHVOList(ItemKindview);

        // 不打新保标识的去掉新保性质
        if ("2".equals(vSvcKind) && !"1".equals(cFreeMaintain)) {
            for (SVCItemKindSHVO item : ItemKindlist) {
                if ("6".equals(item.getvRepClsCode())) {
                    ItemKindlist.remove(item);
                    break;
                }
            }
        }
        // 不打延保标识的，去掉延保性质
        if (!"1".equals(cExtraMaintain)) {
            for (SVCItemKindSHVO item : ItemKindlist) {
                if ("5".equals(item.getvRepClsCode())) {
                    ItemKindlist.remove(item);
                    break;
                }
            }
        }

        return ItemKindlist;
    }

    // 删除委托书校验
    @Override
    public Map<String, Object> deletecheck(DeleteCheckVO deleteCheckVO) {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        List<SVCServiceRequestVODTO> container = deleteCheckVO.getsVCServiceRequestQueryListCM();
        String cValid = "1";
        SVCServiceRequestVODTO selectedSdo = new SVCServiceRequestVODTO();
        if (container != null && container.size() > 0) {
            selectedSdo = container.get(0);
        }

        // 增加删除委托书权限校验

        CheckUserRightVO vo = new CheckUserRightVO();
        vo.setNdid(userInfor.getnDID());
        vo.setUserID(userInfor.getiD());
        vo.setvRight("C7");
        Map<String, Object> str = iInvokeService.checkuserright(userInfor.getnDID(), vo);
        Map<String, String> res = (Map<String, String>) str.get("data");
        Integer returnData = Integer.parseInt(res.get("isEXCE"));
        if (returnData == 0) {

            // 当前登录人没有删除委托书权限
            message.putMessage("SVCMessage", "267");
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 召回行动委托书不允许删除
        String vSvcKind = selectedSdo.getvSvcKind();
        if ("S".equals(vSvcKind) || "V".equals(vSvcKind) || "Z".equals(vSvcKind)) {
            // 该委托书类别不能删除
            message.putMessage("SVCMessage", "175");
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 校验是否有维修项目
        List<SVCServiceRequestItemVODTO> itemList = SelfGetItemByMainID(selectedSdo.getiD());
        if (itemList != null && itemList.size() > 0) {
            message.putMessage("SVCMessage", "083");
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 校验是否有维修领料  调用存储过程判断
        List<SVCServiceRequestItemVODTO> listLL =
                svc0101Mapper.IsExistSPADrawDetail(userInfor.getnDID(), selectedSdo.getiD());
        if (listLL != null && listLL.size() > 0) {
            message.putMessage("SVCMessage", "084");
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 获取预估备件
        List<SVCServiceRequestSpaDTO> SpaList = SelfGetSPAByMainID(selectedSdo.getiD());
        if (SpaList != null && SpaList.size() > 0) {
            message.putMessage("SVCMessage", "125",new String[]{"有预估配件记录，不允许删除"});
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 校验委托书状态
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, selectedSdo.getiD());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);

//        String vRepairStatus = list.get(0).getvRepairStatus();
//        if (!"00".equals(vRepairStatus)) {
//            // 委托书非在修状态，不可删除!
//            message.putMessage("SVCMessage", "043");
//            cValid = "0";
//            map.put("SVCParaTransformCM", cValid);
//            map.put("err", message);
//            return map;
//        }

        if (null != list && !list.isEmpty()) {
            String vRepairStatus = list.get(0).getvRepairStatus();
            if (!"00".equals(vRepairStatus)) {
                // 委托书非在修状态，不可删除!
                message.putMessage("SVCMessage", "043");
                cValid = "0";
                map.put("SVCParaTransformCM", cValid);
                map.put("err", message);
                return map;
            }
        } else {
            message.putMessage("ARCMessage", "001", new String[]{"委托书状态不存在"});
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        // 校验替换车

        DbUnionCommonDto view = new DbUnionCommonDto();
        view.setQueryConditions("a.NDID", 0, userInfor.getnDID());
        view.setQueryConditions("a.NCorID", 0, selectedSdo.getiD());
        view.setQueryConditions("(a.DReturn = '' or a.DReturn is null)", 14, "");
        List<SVCServiceCarUseInfoVO> list1 = svcServiceCarUseInfoVOMapper.sVCServiceCarUseInfoVO(view);
        if (list1.size() > 0) {
            message.putMessage("SVCMessage", "125", new String[]{"该委托书使用了替换车且未归还，不允许删除"});
            cValid = "0";
            map.put("SVCParaTransformCM", cValid);
            map.put("err", message);
            return map;
        }

        map.put("SVCParaTransformCM", cValid);
        return map;
    }

    // 确认删除委托书
    @Override
    public Map<String, Object> deleteconfirm(DeleteCheckVO deleteCheckVO) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        List<SVCServiceRequestVODTO> list = deleteCheckVO.getsVCServiceRequestQueryListCM();

        SVCServiceRequestVODTO selectedSdo = list.get(0);
        if (selectedSdo != null) {
            DbUnionCommonDto SVCVO = new DbUnionCommonDto();
            SVCVO.setQueryConditions("a.iD", 0, selectedSdo.getiD());
            SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            List<SvcServiceRequestViewDTO> svcList = svcServiceRequestViewMapper.query(SVCVO);

            if (svcList != null && svcList.size() > 0) {
                map.put("sVCServiceRequestVO", svcList.get(0));
            }
        }
        return map;
    }

    // 删除委托书
    @Transactional
    @Override
    public Map<String, Object> dodelete(DeleteCheckVO deleteCheckVO) throws IOException {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        LocalDateTime now = LocalDateTime.now();
        // String usewtc = stmCommonService.GetParameters("UseWTC", userInfor.getnDID(), "SVC");
        SVCServiceRequestVODTO SVCServiceRequestVO =
                deleteCheckVO.getsVCServiceRequestQueryListCM().get(0);
        SvcOrderPO svcPO = new SvcOrderPO();
        QueryWrapper<SvcOrderPO> updateSvc = new QueryWrapper<>();
        updateSvc.eq("id", SVCServiceRequestVO.getiD());
        List<SvcOrderPO> svclist = svcPO.selectList(updateSvc);
        BeanUtils.copyProperties(svclist.get(0), svcPO);
        svcPO.setvDeleteReason(SVCServiceRequestVO.getvDeleteReason());
        svcPO.setcDelete(1);

        //上传委托书给C端
//        OrderInfoToSanyAppTask task = new OrderInfoToSanyAppTask(svcPO);
//        ExecutorManager.execute(task);

        svcToSanyAppService.sendToSanyApp(svcPO);

        svcPO.updateById();


//        // 删除委托书捷达共享店传送数据
//        String vSvcFrom = svcPO.getvSvcFrom();
//        String vVin = svcPO.getvVin();
//        String vSvcKind = svcPO.getvSvcKind();
//
//        if (!StringUtils.isNullOrEmpty(vSvcFrom) && vSvcFrom.startsWith("GX")) {
//            Map jdmap = new HashMap();
//            jdmap.put("pdi", "0");
//            jdmap.put("vVin", vVin);
//            jdmap.put("vSvcKind", vSvcKind);
//            jdmap.put("vSvcFrom", vSvcFrom);
//            svc0101_04Service.UPDATESHAREPDI(jdmap);
//        }


        String nDID = svclist.get(0).getnDID();
        DealerPO dealerPO = new DealerPO();
        dealerPO = dealerPO.selectById(nDID);
        String dealer = dealerPO.getvDealer();
        String saleCode = dealerPO.getvSaleCode();

        // 系统重要操作日志
        SysTemOtherLogPO LogPO = new SysTemOtherLogPO();
        LogPO.setId(UUID.randomUUID().toString());
        LogPO.setVType("DelBill");
        LogPO.setDCreate(now);
        LogPO.setDImp(now);
        LogPO.setVTrans("SVC0101");
        LogPO.setVContent(
                "[删除了委托书["
                        + SVCServiceRequestVO.getvBillNO()
                        + "]，客户["
                        + SVCServiceRequestVO.getvCusName()
                        + "]，牌照号["
                        + SVCServiceRequestVO.getvLicenseTag()
                        + "] 说明原因:"
                        + SVCServiceRequestVO.getvDeleteReason()
                        + "");
        LogPO.setVEntity("tt_svc_order");
        LogPO.setNdid(userInfor.getnDID());
        LogPO.setNbid(userInfor.getnBID());
        LogPO.setNOprID(userInfor.getiD());
        LogPO.setVOpr(userInfor.getvPerson());
        LogPO.setVOprName(userInfor.getvPersonName());
        LogPO.insertOrUpdate();

//        //删除elsapro委托书
//        Map<String, String> params = new HashMap<>();
//        params.put("id", svcPO.getiD());
//        params.put("op", "canceled");
//        elsaProService.uploadServiceRequest(params);

        // 来源预约
        if ("0".equals(SVCServiceRequestVO.getvSvcFrom())) {
            // 更新预约单
            List<SVCBookRegisterVO> returnlist = null;
            DbUnionCommonDto view = new DbUnionCommonDto();
            view.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getnSvcFromBillID());
            if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnSvcFromBillID())) {
                returnlist = sVCBookRegisterVOMapper.sVCBookRegisterVO(view, userInfor.getnDID());
            }

            if (returnlist != null && returnlist.size() > 0) {

                SvcBookRegisterPO po = new SvcBookRegisterPO();

                QueryWrapper<SvcBookRegisterPO> updatePO = new QueryWrapper<>();
                updatePO.eq("id", returnlist.get(0).getiD());
                List<SvcBookRegisterPO> listPO = po.selectList(updatePO);
                BeanUtils.copyProperties(listPO.get(0), po);
                po.setvExecuteStatus("01");
                po.setvBillStatus("2");
                po.setdSxrq(LocalDateTime.of(1900, 1, 1, 0, 0, 0));
                po.setvWtsbh("");
                po.setIsTransform(0);

                //更新预约单状态给C端
                BookOrderInfoToSanyAppTask task1 = new BookOrderInfoToSanyAppTask(po);
                ExecutorManager.execute(task1);

                po.updateById();
            }
        }
        // 来源估算
        else if ("1".equals(SVCServiceRequestVO.getvSvcFrom())) {
            // 更新估算单
            DbUnionCommonDto query = new DbUnionCommonDto();
            query.setQueryConditions("a.ID", 0, SVCServiceRequestVO.getnSvcFromBillID());
            List<SVCEstimateViewDTO> SVCEstimateList = svc0201SvcEstimateMapper.sVCEstimateVO(query);
            if (SVCEstimateList != null && SVCEstimateList.size() > 0) {
                SvcEstimatePO po = new SvcEstimatePO();

                QueryWrapper<SvcEstimatePO> updatePo = new QueryWrapper<>();
                updatePo.eq("id", SVCEstimateList.get(0).getiD());
                List<SvcEstimatePO> list = po.selectList(updatePo);
                BeanUtils.copyProperties(list.get(0), po);
                po.setvProcessSt("00");
                po.setnEnterID("");
                po.updateById();

                if (!StringUtils.isNullOrEmpty(po.getnSvcFromBillID())){
                    SvcBookRegisterPO svcBookRegisterPO = new SvcBookRegisterPO();

                    QueryWrapper<SvcBookRegisterPO> updatePO = new QueryWrapper<>();
                    updatePO.eq("id", po.getnSvcFromBillID());
                    List<SvcBookRegisterPO> listPO = svcBookRegisterPO.selectList(updatePO);
                    BeanUtils.copyProperties(listPO.get(0), svcBookRegisterPO);
                    svcBookRegisterPO.setvExecuteStatus("01");
                    svcBookRegisterPO.setvBillStatus("2");
                    svcBookRegisterPO.setdSxrq(LocalDateTime.of(1900, 1, 1, 0, 0, 0));
                    svcBookRegisterPO.setvWtsbh("");

                    //更新预约单状态给C端
                    BookOrderInfoToSanyAppTask task1 = new BookOrderInfoToSanyAppTask(svcBookRegisterPO);
                    ExecutorManager.execute(task1);
                    svcBookRegisterPO.updateById();
                }

            }
        } else if ("5".equals(SVCServiceRequestVO.getvSvcFrom())) {
            // 更新延保估算单
            //            IView SVCExtendedWarrantyEstimateView =
            // ViewDefFactory.CreateView("SVCExtendedWarrantyEstimateVO");
            //            SVCExtendedWarrantyEstimateView.AddConditionRow("a.ID", "='" +
            // SVCServiceRequestVO.GetGuid("NSvcFromBillID").ToString() + "'");
            //            List<ISDO> extEstList = SVCExtendedWarrantyEstimateView.ExecQuerySDO();
            //            if (extEstList.Count > 0)
            //            {
            //                extEstList[0].SetProperty("VRepairStatus", "00");
            //                EntityDefFactory.Update(extEstList[0]);
            //            }
        }
//        if ("8".equals(SVCServiceRequestVO.getvSvcKind())
//                || "P".equals(SVCServiceRequestVO.getvSvcKind())) {
//            // 更新整车库存日志PDI、预PDI标识
//            // 更新标识给sale库
//            SaleCMPDI saleCMPDI = new SaleCMPDI();
//            saleCMPDI.setPdi("0");
//            saleCMPDI.setvSvcKind(SVCServiceRequestVO.getvSvcKind());
//            saleCMPDI.setvVin(SVCServiceRequestVO.getvVin());
//
//            logger.error("dodelete  删除委托书时 更新整车库存日志PDI、预PDI标识 ");
//            logger.error("svcKind:{} ", SVCServiceRequestVO.getvSvcKind());
//            logger.error("vvin:{} ", SVCServiceRequestVO.getvVin());
//
//            Map<String, Object> map1 = ssalFeignClient.updatepdi(userInfor.getnDID(), saleCMPDI);
//
//            // 删除委托书同步到捷达
////            String vVin = SVCServiceRequestVO.getvVin();
////            String vSvcKind = SVCServiceRequestVO.getvSvcKind();
////            Map jdmap = new HashMap();
////            jdmap.put("pdi", "0");
////            jdmap.put("vVin", vVin);
////            jdmap.put("vSvcKind", vSvcKind);
////            jdmap.put("vSvcFrom", saleCode);
////            svc0101_04Service.UPDATESHAREPDI(jdmap);
//        }

//        // ==================加在最后删除委托书后调用会员删除会员占用信息  yubingsen 2020-10-24 ===================================
//        Map deleteSvcOrderVipRes = svcToVipService.deleteVIPItemAndSpaBySvcOrder(SVCServiceRequestVO.getiD());
//        logger.info("委托书删除调用会员接口返回值:{}", deleteSvcOrderVipRes);
//

        String useSanyCrm = stmCommonService.GetParameters("useSanyCrm", userInfor.getnDID(), "SVC");
        if (("1").equals(useSanyCrm)) {
            svcToSanyCrmService.upLoadObjectIDStatus(svcPO.getiD());
             if(("02").equals(SVCServiceRequestVO.getvOrderType())) {
                //委托书信息
                String[] crmOrderNos = SVCServiceRequestVO.getvObjectID().split(";");
                SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
                svcSaleOrderInfoDTO.setiVOBJECTID(crmOrderNos[1]);
                svcSaleOrderInfoDTO.setvStatus("CANC");
                List<SVCServiceRequestSpaDTO> svcServiceRequestSpaDTOS = new ArrayList<>();

                Map mapOrder = new HashMap();
                mapOrder.put("spas",svcServiceRequestSpaDTOS);
                mapOrder.put("svcSaleOrderInfoDTO",svcSaleOrderInfoDTO);
                svcToSanyCrmService.modifySaleOrder(mapOrder);
            }

        }
        message.putMessage("SREMessage", "008");
        map.put("infor", message);
        return map;
    }

    // 集成FD
    @Override
    public Map<String, Object> fdbill(SvcServiceRequestViewDTO svcServiceRequestVO) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = svcServiceRequestVO;
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.id", 0, SVCServiceRequestVO.getiD());
        List<SvcServiceRequestViewDTO> List = svcServiceRequestViewMapper.query(SVCVO);

        if (List != null && List.size() > 0) {
            // Out.SetSDO("SVCServiceRequestVO", List[0]);
            DbUnionCommonDto STMPersonQASHVO = new DbUnionCommonDto();
            // 给视图中的参数赋值，如果有参数但是没有赋值则形成的sql中就没有该参数的语句
            STMPersonQASHVO.setQueryConditions("a.id", 0, List.get(0).getnSVCAdviserID());
            STMPersonQASHVO.setQueryConditions("a.nBID", 0, userInfor.getnBID());
            Page<STMPersonQASHVO> page = new Page<STMPersonQASHVO>(1, 20);
            List<STMPersonQASHVO> PersongList =
                    sTMPersonQASHVOMapper.sTMPersonQASHVO(page, STMPersonQASHVO);

            String VSVCAdviserName = "";
            if (PersongList != null && PersongList.size() > 0) {
                VSVCAdviserName = PersongList.get(0).getvPersonName();
            }
            map.put("dms_bodynr", List.get(0).getvVin());
            map.put("dms_carnum", List.get(0).getvLicenseTag());
            map.put("dms_wtsh", List.get(0).getvBillNO());
            LocalDateTime den = List.get(0).getdEnter();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = den.format(formatter);
            map.put("dms_wtsdat", formattedDateTime);
            map.put("dms_scname", VSVCAdviserName);
            map.put("dms_montor", List.get(0).getvEngineNo());
            map.put("dms_zxkm", List.get(0).getnMileage());
            map.put("dms_clgs", List.get(0).getvCarBelong());
            map.put("dms_khms", List.get(0).getvCusDesc());
            map.put("dms_gzms", List.get(0).getvBreakdownDesc());
            map.put("dms_warning", List.get(0).getcWarning());
            map.put("dms_warningbillnos", List.get(0).getvWarningBillNos());

            int cwarring = 0;
            if (List.get(0).getcWarning() != null) {
                cwarring = List.get(0).getcWarning();
            }

            if (cwarring == 1) {
                map.put("BJBS", "1");
            } else {
                map.put("BJBS", "0");
            }
            if ("0L".equals(List.get(0).getvVin().substring(6, 8))
                    || "0M".equals(List.get(0).getvVin().substring(6, 8)) || "L0".equals(List.get(0).getvVin().substring(6, 8))) {
                map.put("brand", "J");
            } else if ("D49F66C6-52A2-4D87-B5DC-C0698E2A8E74"
                    .equals(userInfor.getnCustGroupId().toUpperCase())) {
                map.put("brand", "V");
            } else {
                map.put("brand", "");
            }

            // NSVCAdviserID
        }
        return map;
    }

    // 批量保存建议维修项目
    @Override
    public Map<String, Object> batchaddsugitem(BatchAddSugItemVO batchAddSugItemVO) {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequestVO = batchAddSugItemVO.getsVCServiceRequestVO();
        SVCParaTransformCM SVCParaTransformCM = batchAddSugItemVO.getsVCParaTransformCM();
        String NMainID = SVCServiceRequestVO.getiD();

        List<SVCBatchSelectItemCM> ItemList = batchAddSugItemVO.getItemTable();

        String NStdID = UUID.randomUUID().toString();

        LocalDateTime now = LocalDateTime.now();

        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.id", 0, SVCServiceRequestVO.getiD());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);

        if (list != null && list.size() > 0) {
            if (!"00".equals(list.get(0).getvRepairStatus())) {
                // 委托书非在修状态，不可执行操作！
                message.putMessage("SVCMessage", "077");
                map.put("err", message);
                return map;
            } else {
                SVCServiceRequestVO = list.get(0);
            }
        }

        // 校验并保存项目
        for (SVCBatchSelectItemCM SelectItem : ItemList) {
            // 校验是否存在重复项目
            if (!"ZJ990000".equals(SelectItem.getvVItem())) {
                if (SelfIsExist("SVCServiceRequestSugeestMitVO", NMainID, "NItemID", SelectItem.getiD())) {
                    message.putMessage(
                            "SVCMessage", "006", new String[]{"项目", SelectItem.getvItem()}); // {0}{1}已经存在!
                    map.put("err", message);
                    return map;
                }
            } else {
                String vitem = SelectItem.getvVItem();
                if ((!StringUtils.isNullOrEmpty(vitem) && vitem.length() != 8)
                        && (!"ZJ99".equals(vitem.substring(0, 4)))) {
                    message.putMessage(
                            "SVCMessage",
                            "061",
                            new String[]{SelectItem.getvVItem()}); // 项目代码{0}不符合规则【ZJ99####】!
                    map.put("infor", message);
                }
            }

            NStdID = SelectItem.getnStdID();
            SvcOrderSugeestMitPO SVCServiceRequestSugeestMitVO = new SvcOrderSugeestMitPO();

            SVCServiceRequestSugeestMitVO.setnMainID(NMainID);
            SVCServiceRequestSugeestMitVO.setnItemID(SelectItem.getiD());
            SVCServiceRequestSugeestMitVO.setvItem(SelectItem.getvItem());
            SVCServiceRequestSugeestMitVO.setvItemName(SelectItem.getvItemName());
            SVCServiceRequestSugeestMitVO.setnManhaurFee(SelectItem.getnManhaurFee());
            SVCServiceRequestSugeestMitVO.setnManhaur(SelectItem.getnManhaur());
            SVCServiceRequestSugeestMitVO.setnDID(userInfor.getnDID());
            SVCServiceRequestSugeestMitVO.setvItemProperty(SelectItem.getvItemType());
            SVCServiceRequestSugeestMitVO.setcUsed(0);
            SVCServiceRequestSugeestMitVO.insertOrUpdate();

            SvcOrderSugeestMitDelPO delPO = new SvcOrderSugeestMitDelPO();
            QueryWrapper<SvcOrderSugeestMitDelPO> delQueryPo = new QueryWrapper<>();
            delQueryPo.eq("NMainID", SVCServiceRequestSugeestMitVO.getnMainID());
            delQueryPo.eq("VItem", SVCServiceRequestSugeestMitVO.getvItem());
            delQueryPo.eq("NDID", SVCServiceRequestSugeestMitVO.getnDID());
            List<SvcOrderSugeestMitDelPO> listdelpo = delPO.selectList(delQueryPo);
            if (listdelpo != null && listdelpo.size() > 0) {
                BeanUtils.copyProperties(listdelpo.get(0), delPO);
                delPO.deleteById();
            }
        }

        // 反写主表NStdID
        if (ItemList != null && ItemList.size() > 0) {
            SVCServiceRequestVO.setnStdID(NStdID);
        }

        // 获取建议项目
        List<SVCServiceRequestSugeestMitVO> sugItemList =
                svc0101_04Service.SelfGetSugItemByMainID(
                        list.get(0).getiD(), list.get(0).getvVin(), batchAddSugItemVO.getIsHasHistory());
        map.put("sVCServiceRequestSugeestMitVO", sugItemList);

        message.putMessage("SVCMessage", "005");
        map.put("infor", message);
        return map;
    }

    // 复制委托书
    @Override
    public Map<String, Object> copysvc(CopySvcVO copySvcVO) throws Exception {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequest = copySvcVO.getsVCServiceRequest();
        Svc0201ParaTransformCMDTO SVCParaTransformCM = copySvcVO.getsVCParaTransformCM();
        SVCParaTransformCM.setcValid(1);
        String vMessageCode = "";
        SvcServiceRequestViewDTO SVCServiceRequestVO = new SvcServiceRequestViewDTO();

        LocalDateTime now = LocalDateTime.now();
        // 启用迷你店
        //        String MINIQY = stmCommonService.GetParameters("MINIQY", userInfor.NDefaultBID,
        // "SYS");

        //        IView view = ViewDefFactory.CreateView("STMQIMBranchVO");
        //        view.AddConditionRow("a.ID", "='" + userInfor.NDefaultBID + "'");
        //        view.AddConditionRow("isnull(a.cStop,'0')", "='0'");
        //        List<ISDO> BranchList = view.ExecQuerySDO();
        //        //网点代码
        //        string vBranchCode = "";
        //        bool cMainFlag = true;
        //        if (BranchList.Count > 0)
        //        {
        //            vBranchCode = BranchList[0].GetString("VBranchCode");
        //            cMainFlag = BranchList[0].GetBoolean("CMainFlag");
        //        }

        // 设置数据字典
        SetEnterDict(userInfor.getnDID());

        // 校验委托类别是否重复
        Map<String, Object> resmaps =
                CheckCopySvcKind(
                        userInfor,
                        SVCServiceRequest.getiD(),
                        SVCServiceRequest.getvSvcKind(),
                        SVCServiceRequestVO);
        SVCServiceRequestVO = (SvcServiceRequestViewDTO) resmaps.get("sVCServiceRequestVO");
        String cValid = resmaps.get("err") + "";
        if (StringUtils.isNullOrEmpty(cValid) || "null".equals(cValid)) {
            SVCServiceRequest.setvBillNO(SVCServiceRequestVO.getvBillNO());
            // 校验生成新委托书号是否存在
            cValid =
                    CheckCopyBillNO(
                            userInfor,
                            SVCServiceRequest.getvSvcKind()
                                    + SVCServiceRequestVO.getvBillNO()
                                    .substring(1, SVCServiceRequestVO.getvBillNO().length()));
            if (StringUtils.isNullOrEmpty(cValid)) {
                // 取系统参数 复制委托书的送修时间以当前系统时间为准

                String vCopySvcCurrDate =
                        stmCommonService.GetParameters("CopySvcCurrDate", userInfor.getnDID(), "SVC");
                String MINI = stmCommonService.GetParameters("MINIQY", userInfor.getnDID(), "SYS");
//                if (StringUtils.isNullOrEmpty(SVCParaTransformCM.getvPara())) {
//                    LocalDateTime date = LocalDateTime.now();
//                    String vBillNo =
//                            fwSystemOrderNoService.getSystemOrderNoYyyyMMdd(
//                                    "D",
//                                    "D",
//                                    userInfor.getnDID(),
//                                    LocalDateTimeUtils.localDateTimeToString(date, "yyyyMMdd"),
//                                    "3");
//
//                    vBillNo = vBillNo.substring(1, vBillNo.length());
//                    // 开启迷你店
//                    if ("1".equals(MINI)) {
//                        // 获取网点代码替换到委托书前两位 20200909004
//                        String vBranchCode = "";
//                        TmBranchMqPO tmBranch = new TmBranchMqPO();
//                        tmBranch = tmBranch.selectById(userInfor.getnBID());
//                        vBranchCode = tmBranch.getvBranchCode();
//                        vBillNo = vBranchCode + vBillNo.substring(2);
//                    }
//                    SVCParaTransformCM.setvPara(vBillNo);
//                }
                if (!StringUtils.isNullOrEmpty(vCopySvcCurrDate) && "1".equals(vCopySvcCurrDate)) {
                    SVCServiceRequestVO.setdEnter(now);
                    LocalDateTime dPickUp = GetPickUpBegin(now, SVCServiceRequest.getnBID());
                    SVCServiceRequestVO.setdPickUp(dPickUp);
                    LocalDateTime dRepair = GetRepairBegin(dPickUp, SVCServiceRequest.getnBID());
                    SVCServiceRequestVO.setdEstimateRepair(dRepair);
                    SVCServiceRequestVO = GetFinishBegin(SVCServiceRequestVO);

                } else {
                    SVCServiceRequestVO.setdEnter(SVCServiceRequestVO.getdEnter().plusSeconds(1));
                    SVCServiceRequestVO.setdPickUp(SVCServiceRequestVO.getdPickUp().plusSeconds(1));
                    SVCServiceRequestVO.setdEstimateRepair(
                            SVCServiceRequestVO.getdEstimateRepair().plusSeconds(1));
                    SVCServiceRequestVO.setdPromiseFinish(
                            SVCServiceRequestVO.getdPromiseFinish().plusSeconds(1));
                }

                // 计算JD和IA标识

                // 计算JD和IA标识
                LocalDateTime dLicense = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
                String local = SVCServiceRequestVO.getdLicense() + "";
                if (!StringUtils.isNullOrEmpty(local)) {
                    dLicense = SVCServiceRequestVO.getdEstimateRepair();
                }

                JDIAResult serviceResult =
                        pUCCommonService.getJDIA(SVCServiceRequestVO.getdLicense(), now, userInfor.getnBID());
                int cJD = serviceResult.getcJD();
                int cIA = serviceResult.getcIA();

                SVCServiceRequestVO.setcJD(cJD);
                SVCServiceRequestVO.setcIA(cIA);

                SVCServiceRequestVO.setUpdateOn(0L);
                SVCServiceRequestVO.setCreateOn(now);
                SVCServiceRequestVO.setiD("");
                SVCServiceRequestVO.setvSvcKind(SVCServiceRequest.getvSvcKind());
                SVCServiceRequestVO.setvBillNO(
                        SVCServiceRequest.getvSvcKind() + "-" + SVCParaTransformCM.getvPara());
                SVCServiceRequestVO.setvSvcFrom("2");
                SVCServiceRequestVO.setnSvcFromBillID("");
                SVCServiceRequestVO.setvRepairStatus("00");
                SVCServiceRequestVO.setcSettle(0);
                SVCServiceRequestVO.setcFreeMaintain(0);
                SVCServiceRequestVO.setcExtraMaintain(0);
                if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(resmaps.get("vCusAddr"))) {
                    SVCServiceRequestVO.setvAddrSre(resmaps.get("vCusAddr").toString());
                }
                SVCServiceRequestVO.setvZHXDFJ("");
                SVCServiceRequestVO.setcUploadjkda(0);
                SVCServiceRequestVO.setvZXYX("");
                SVCServiceRequestVO.setcActive(0);
                SVCServiceRequestVO.setcUseVipCard(0);
                SVCServiceRequestVO.setcArrear(0);
                SVCServiceRequestVO.setcSpread(0);
                SVCServiceRequestVO.setvUpgradeNO("");
                SVCServiceRequestVO.setdAdt(LocalDateTime.of(1900, 1, 1, 0, 0, 0));
                SVCServiceRequestVO.setnAdtID("");
                SVCServiceRequestVO.setdCheckOut(LocalDateTime.of(1900, 1, 1, 0, 0, 0));
                SVCServiceRequestVO.setcSeasonActive(0);
                SVCServiceRequestVO.setvTeams("");
                SVCServiceRequestVO.setRecordVersion(1);
                SVCServiceRequestVO.setvObjectID("");
                // SVCServiceRequestVO.SetProperty("CWarning", SVCServiceRequest.GetProperty("CWarning"));
                // SVCServiceRequestVO.SetProperty("VWarningBillNos",
                // SVCServiceRequest.GetString("VWarningBillNos"));
                // SVCServiceRequestVO.setvwa("VWarningDealBillNos",
                // SVCServiceRequest.GetString("VWarningDealBillNos"));
                map.put("sVCServiceRequestVO", SVCServiceRequestVO);
            } else {
                SVCParaTransformCM.setcValid(0);
                SVCParaTransformCM.setvMessageCode(vMessageCode);
            }
        } else {
            SVCParaTransformCM.setcValid(0);
            SVCParaTransformCM.setvMessageCode(vMessageCode);
        }

        // 查询客户档案填充省市区县 和客户详细地址
        // 增加省市区县list
        CustomerPO customerPO = new CustomerPO();
        QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vCus", SVCServiceRequest.getvCus());
        queryWrapper.eq("ndid", userInfor.getnDID());
        List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
        if (cuslistPO != null && cuslistPO.size() > 0) {
            customerPO = cuslistPO.get(0);
            List<STMCityVODTO> vCityLinklist = new ArrayList<>();
            vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
            SVCServiceRequestVO.setvCityLink(vCityLinklist);
            SVCServiceRequestVO.setvCusAddrDetail(customerPO.getvCusAddrDetail());
            SVCServiceRequestVO.setnCityID(customerPO.getnCityID());

            CustomerPO customerPO1 = cuslistPO.get(0);
            String vAddrStr = customerPO1.getvProvince() + "," + customerPO1.getvCity();
            if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(customerPO1.getvArea())){
                vAddrStr = vAddrStr + "," + customerPO1.getvArea();
            }
            SVCServiceRequestVO.setvAddrSre(vAddrStr);
        }

        map.put("sVCParaTransformCM", SVCParaTransformCM);
        map.put("sVCServiceRequest", SVCServiceRequestVO);
        return map;
    }

    // 调用复制委托书屏
    @Override
    public Map<String, Object> callcopysvc(CopySvcVO copySvcVO) throws Exception {

        Map<String, Object> map = new HashMap<>();

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        //        ISYSSeriNumService seriNumService =
        // (ISYSSeriNumService)this.GetService("SYSSeriNumService");
        //        ISTMCommonService STMCommonService =
        // (ISTMCommonService)this.GetService("STMCommonService");
        LocalDateTime now = LocalDateTime.now();
        //        //启用迷你店
        //        string MINIQY = STMCommonService.GetParameters("MINIQY", userInfor.NDefaultBID,
        // "SYS");
        //
        //        IView view = ViewDefFactory.CreateView("STMQIMBranchVO");
        //        view.AddConditionRow("a.ID", "='" + userInfor.NDefaultBID + "'");
        //        view.AddConditionRow("isnull(a.cStop,'0')", "='0'");
        //        List<ISDO> BranchList = view.ExecQuerySDO();
        //        //网点代码
        //        string vBranchCode = "";
        //        bool cMainFlag = true;
        //        if (BranchList.Count > 0)
        //        {
        //            vBranchCode = BranchList[0].GetString("VBranchCode");
        //            cMainFlag = BranchList[0].GetBoolean("CMainFlag");
        //        }
        LocalDateTime date = LocalDateTime.now();
        String vBillNo = "";
//                fwSystemOrderNoService.getSystemOrderNoYyyyMMdd(
//                        "D",
//                        "D",
//                        userInfor.getnDID(),
//                        LocalDateTimeUtils.localDateTimeToString(date, "yyyyMMdd"),
//                        "3");
//
//        vBillNo = vBillNo.substring(1, vBillNo.length());

        //        List<string> seriNum = seriNumService.GenerateSeriNumbers("WTS", null, now,
        // vBranchCode, 1);
        //        string vNewBillNO = seriNum[0];
        //        if (!string.IsNullOrEmpty(MINIQY) && MINIQY == "1")
        //        {
        //            vNewBillNO = vBranchCode + vNewBillNO.Substring(2);
        //        }

        SvcServiceRequestViewDTO SVCServiceRequest = copySvcVO.getsVCServiceRequest();
        Svc0201ParaTransformCMDTO SVCParaTransformCM = new Svc0201ParaTransformCMDTO();

        SVCParaTransformCM.setnCusGroupID(userInfor.getnCustGroupId());
        SVCParaTransformCM.setvPara(vBillNo);
        map.put("sVCServiceRequest", SVCServiceRequest);
        map.put("sVCParaTransformCM", SVCParaTransformCM);

        // ISDO DynamicSdo = SDODefFactory.CreateDynamicSDO();
        // DynamicSdo.SetProperty("Newbillno", seriNum[0]);
        // Out.SetSDO("UserCustomDynamicData", DynamicSdo);
        map.put("newbillno", vBillNo);

        return map;
    }

    // 复制委托书校验
    @Override
    public Map<String, Object> dialogcopysvc(CopySvcVO copySvcVO) {

        Map<String, Object> map = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        SvcServiceRequestViewDTO SVCServiceRequest = copySvcVO.getsVCServiceRequest();
        Svc0201ParaTransformCMDTO SVCParaTransformCM = copySvcVO.getsVCParaTransformCM();

        SVCParaTransformCM.setcValid(1);
        String vMessageCode = "";
        SvcServiceRequestViewDTO SVCServiceRequestVO = new SvcServiceRequestViewDTO();
        String VPara;
        VPara = "-" + SVCParaTransformCM.getvPara();
        Map<String, Object> resmaps =
                CheckCopySvcKind(
                        userInfor,
                        SVCServiceRequest.getiD(),
                        SVCServiceRequest.getvSvcKind(),
                        SVCServiceRequestVO);
        SVCServiceRequestVO = (SvcServiceRequestViewDTO) resmaps.get("sVCServiceRequestVO");
        String cValid = resmaps.get("err") + "";
        vMessageCode = cValid;
        if (StringUtils.isNullOrEmpty(cValid) || "null".equals(cValid)) {
            cValid = CheckCopyBillNO(userInfor, SVCServiceRequest.getvSvcKind() + VPara);
            if (!StringUtils.isNullOrEmpty(cValid)) {
                SVCParaTransformCM.setcValid(0);
                SVCParaTransformCM.setvMessageCode(cValid);
            }
        } else {
            SVCParaTransformCM.setcValid(0);
            SVCParaTransformCM.setvMessageCode(vMessageCode);
        }
        // SVCServiceRequest.SetProperty("VBillNO", SVCServiceRequest.GetString("VSvcKind") + VPara);
        map.put("sVCParaTransformCM", SVCParaTransformCM);
        map.put("sVCServiceRequest", SVCServiceRequest);
        return map;
    }

    // 调用修改委托书类别
    @Override
    public Map<String, Object> callchangekind(CopySvcVO copySvcVO) {

        Map<String, Object> map = new HashMap<>();

        SvcServiceRequestViewDTO SVCServiceRequestVO = copySvcVO.getsVCServiceRequest();
        Svc0201ParaTransformCMDTO SVCParaTransformCM = new Svc0201ParaTransformCMDTO();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        SVCParaTransformCM.setnCusGroupID(userInfor.getnCustGroupId());
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        map.put("sVCParaTransformCM", SVCParaTransformCM);

        return map;
    }

    // 校验修改委托书类别
    @Override
    public Map<String, Object> checkchangekind(CopySvcVO copySvcVO) {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        SvcServiceRequestViewDTO SVCServiceRequestVO = copySvcVO.getsVCServiceRequest();
        Svc0201ParaTransformCMDTO SVCParaTransformCM = copySvcVO.getsVCParaTransformCM();
        SVCParaTransformCM.setcValid(1);
        SVCParaTransformCM.setvMessageCode("");
        // 校验委托书状态
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getiD());
        //判断如果没有委托书ID，强制返回不执行
        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getiD())) {
            throw new DmsBizException(509, "请选择委托书后再更换类别！");
        }
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        SvcServiceRequestViewDTO SVCServiceRequest = new SvcServiceRequestViewDTO();
        if (list != null && list.size() > 0) {
            SVCServiceRequest = list.get(0);
        }

        String vRepairStatus = SVCServiceRequest.getvRepairStatus();

        String vSvcKindOld = SVCServiceRequestVO.getvBillNO().substring(0, 1);
        String vSvcKindNew = SVCServiceRequestVO.getvSvcKind();

        if (vSvcKindOld != null && vSvcKindOld.equals(vSvcKindNew)) {
            // 新委托书类别不能与原委托书类别相同!
            SVCParaTransformCM.setcValid(0);
            message.putMessage("SVCMessage", "046");
            map.put("err", message);
            SVCParaTransformCM.setvMessageCode("046");
            map.put("sVCParaTransformCM", SVCParaTransformCM);
            return map;
        }

        if ("S".equals(vSvcKindNew) || "V".equals(vSvcKindNew) || "Z".equals(vSvcKindNew)) {
            // 当前委托书类别不能修改成行动召回类!
            SVCParaTransformCM.setcValid(0);
            message.putMessage("SVCMessage", "179");
            map.put("err", message);
            SVCParaTransformCM.setvMessageCode("179");
            map.put("sVCParaTransformCM", SVCParaTransformCM);
            return map;
        }

        if ("E".equals(vSvcKindNew)) {
            // 不可修改为该委托书类别！
            SVCParaTransformCM.setcValid(0);
            message.putMessage("SVCMessage", "193");
            map.put("err", message);
            SVCParaTransformCM.setvMessageCode("193");
            map.put("sVCParaTransformCM", SVCParaTransformCM);
            return map;
        }

        String vMessageCode = "";
        String isValid =
                CheckCopyBillNO(
                        userInfor,
                        SVCServiceRequestVO.getvSvcKind()
                                + SVCServiceRequestVO.getvBillNO()
                                .substring(1, SVCServiceRequestVO.getvBillNO().length()));
        vMessageCode = isValid;
        if ("1".equals(SVCParaTransformCM.getcValid().toString())
                && (!StringUtils.isNullOrEmpty(isValid))) {
            // 委托书号已存在
            SVCParaTransformCM.setcValid(0);
            SVCParaTransformCM.setvMessageCode(vMessageCode);
            map.put("sVCParaTransformCM", SVCParaTransformCM);
            return map;
        }

        if ("1".equals(SVCParaTransformCM.getcValid().toString()) && !"00".equals(vRepairStatus)) {
            // 委托书非在修状态，不可执行操作！
            SVCParaTransformCM.setcValid(0);
            SVCParaTransformCM.setvMessageCode("077");
            message.putMessage("SVCMessage", "077");
            map.put("err", message);
            map.put("sVCParaTransformCM", SVCParaTransformCM);
            return map;
        }

        if ("1".equals(SVCParaTransformCM.getcValid().toString())) {
            // 校验是否有维修领料
            List<SVCServiceRequestItemVODTO> drawList =
                    svc0101Mapper.IsExistSPADrawDetail(userInfor.getnDID(), SVCServiceRequestVO.getiD());
            // 如果已领料
            if (drawList != null && drawList.size() > 0) {

                // SVCBusConfigVO--->对应SvcBusConfigDTO
                DbUnionCommonDto searchEntity5 = new DbUnionCommonDto();
                searchEntity5.setQueryConditions("a.NCusGroupID", 0, userInfor.getnCustGroupId());
                List<SvcBusConfigPO> busList = sVCBusConfigMapper.getSvcBusConfigDTOList(searchEntity5);

                String vSystemClsPropOld = "";
                String vSystemClsPropNew = "";

                for (SvcBusConfigPO SVCBusConfigVO : busList) {
                    if (vSvcKindOld.equals(SVCBusConfigVO.getvSvcCls())) {
                        vSystemClsPropOld = SVCBusConfigVO.getvSystemClsProp();
                    } else if (vSvcKindNew.equals(SVCBusConfigVO.getvSvcCls())) {
                        vSystemClsPropNew = SVCBusConfigVO.getvSystemClsProp();
                    }
                }

                // 由收费改为免费
                if ("1".equals(vSystemClsPropOld) && "0".equals(vSystemClsPropNew)) {
                    SVCParaTransformCM.setcValid(0);
                    SVCParaTransformCM.setvMessageCode("081");
                    message.putMessage("SVCMessage", "081");
                    map.put("err", message);
                    map.put("sVCParaTransformCM", SVCParaTransformCM);
                    return map;
                }
                // 由免费改为收费
                else if ("0".equals(vSystemClsPropOld) && "1".equals(vSystemClsPropNew)) {
                    SVCParaTransformCM.setcValid(0);
                    SVCParaTransformCM.setvMessageCode("082");
                    message.putMessage("SVCMessage", "082");
                    map.put("err", message);
                    map.put("sVCParaTransformCM", SVCParaTransformCM);
                    return map;
                }
                // 修改内修类别
                else if ("9".equals(vSvcKindOld) || "9".equals(vSvcKindNew)) {
                    SVCParaTransformCM.setcValid(0);
                    SVCParaTransformCM.setvMessageCode("227");
                    message.putMessage("SVCMessage", "227");
                    map.put("err", message);
                    map.put("sVCParaTransformCM", SVCParaTransformCM);
                    return map;
                }
            }
        }

        SVCServiceRequestVO.setvBillNO(
                vSvcKindNew
                        + SVCServiceRequestVO.getvBillNO()
                        .substring(1, SVCServiceRequestVO.getvBillNO().length()));
        map.put("sVCParaTransformCM", SVCParaTransformCM);
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);

        // 委托书类别变更调用透明车间接口删除原委托书
        OrderInfoToEwsTask task = new OrderInfoToEwsTask(userInfor.getnDID(), SVCServiceRequestVO.getiD(), "D");
        ExecutorManager.execute(task);

        return map;
    }

    // 执行修改委托书类别
    @Override
    public Map<String, Object> changekind(CopySvcVO copySvcVO) {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequestVO = copySvcVO.getsVCServiceRequest();
        String vSvcKind = SVCServiceRequestVO.getvSvcKind();
        String vBillNO = SVCServiceRequestVO.getvBillNO();
        String vOldBillNO = "";

        // 更新委托书类别
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getiD());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);

        if (list != null && list.size() > 0) {
            // 修改类别前先调用此过程
            svc0101Mapper.DMSVDD001Before(SVCServiceRequestVO.getiD());

            SVCServiceRequestVO = list.get(0);
            vOldBillNO = SVCServiceRequestVO.getvBillNO();
            SVCServiceRequestVO.setvSvcKind(vSvcKind);
            SVCServiceRequestVO.setvBillNO(vBillNO);

            if ("0".equals(vSvcKind)) {
                SVCServiceRequestVO.setcFirstMT(1);
                SVCServiceRequestVO.setcCLM(0);
            } else if ("1".equals(vSvcKind)
                    || "G".equals(vSvcKind)
                    || "S".equals(vSvcKind)
                    || "V".equals(vSvcKind)
                    || "Z".equals(vSvcKind)) {
                SVCServiceRequestVO.setcFirstMT(0);
                SVCServiceRequestVO.setcCLM(1);
            } else {
                SVCServiceRequestVO.setcFirstMT(0);
                SVCServiceRequestVO.setcCLM(0);
            }

            SvcOrderPO svcop = new SvcOrderPO();
            BeanUtils.copyProperties(SVCServiceRequestVO, svcop);

            // 委托书类别变更调用透明车间接口新建工单
//            OrderInfoToSanyAppTask task = new OrderInfoToSanyAppTask(svcop);
//            ExecutorManager.execute(task);
            svcToSanyAppService.sendToSanyApp(svcop);

            svcop.insertOrUpdate();


            // 来源预约
            if ("0".equals(SVCServiceRequestVO.getvSvcFrom())) {
                // 更新预约单
                DbUnionCommonDto view = new DbUnionCommonDto();
                view.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getnSvcFromBillID());
                List<SVCBookRegisterVO> SVCBookRegisterList = null;
                if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnSvcFromBillID())) {
                    SVCBookRegisterList = sVCBookRegisterVOMapper.sVCBookRegisterVO(view, userInfor.getnDID());
                }

                if (SVCBookRegisterList != null && SVCBookRegisterList.size() > 0) {

                    SvcBookRegisterPO po = new SvcBookRegisterPO();

                    QueryWrapper<SvcBookRegisterPO> updatePO = new QueryWrapper<>();
                    updatePO.eq("id", SVCBookRegisterList.get(0).getiD());
                    List<SvcBookRegisterPO> listPO = po.selectList(updatePO);
                    BeanUtils.copyProperties(listPO.get(0), po);
                    po.setvExecuteStatus("02");
                    po.setvBillStatus("3");
                    po.setdSxrq(SVCServiceRequestVO.getdEnter());
                    po.setvWtsbh(SVCServiceRequestVO.getvBillNO());

                    //更新预约单状态给C端
                    BookOrderInfoToSanyAppTask task1 = new BookOrderInfoToSanyAppTask(po);
                    ExecutorManager.execute(task1);
                    po.updateById();


                }
            }

            // 将原委托书编号对应FD单CNew置为false
            ClmFdbillPO clmPO = new ClmFdbillPO();
            QueryWrapper<ClmFdbillPO> clmquery = new QueryWrapper<>();
            clmquery.eq("VSvcBillNo", vOldBillNO);
            clmquery.eq("NDID", SVCServiceRequestVO.getnDID());
            List<ClmFdbillPO> CLMFDBillList = clmPO.selectList(clmquery);
            if (CLMFDBillList != null && CLMFDBillList.size() > 0) {
                for (ClmFdbillPO CLMFDBillVO : CLMFDBillList) {
                    BeanUtils.copyProperties(CLMFDBillVO, clmPO);
                    clmPO.setcNew(0);

                    clmPO.insertOrUpdate();
                }
            }
        }

        // 取默认性质
        // SVCBusConfigVO--->对应SvcBusConfigDTO
        DbUnionCommonDto searchEntity5 = new DbUnionCommonDto();
        // 客户组ID
        searchEntity5.setQueryConditions("a.NCusGroupID", 0, "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74");
        searchEntity5.setQueryConditions("a.VSvcCls", 0, SVCServiceRequestVO.getvSvcKind());
        List<SvcBusConfigPO> SVCBusConfigList =
                sVCBusConfigMapper.getSvcBusConfigDTOList(searchEntity5);
        String vDefaultKind = "";
        String vDefaultKindName = "";
        if (SVCBusConfigList != null && SVCBusConfigList.size() > 0) {
            vDefaultKind = SVCBusConfigList.get(0).getvRepClsCode();
            vDefaultKindName = SVCBusConfigList.get(0).getvRepClsName();
        }

        // 更新项目性质
        List<SVCServiceRequestItemVODTO> itemList = SelfGetItemByMainID(SVCServiceRequestVO.getiD());
        if (itemList != null && itemList.size() > 0) {
            for (SVCServiceRequestItemVODTO item : itemList) {
                boolean isExist = false;
                for (SvcBusConfigPO configItem : SVCBusConfigList) {
                    if (configItem.getvRepClsCode() != null
                            && configItem.getvRepClsCode().equals(item.getvKind())) {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist) {
                    item.setvKind(vDefaultKind);
                    item.setvKindName(vDefaultKindName);
                }

                item.setvWorkProp(vSvcKind);
                SvcOrderItemPO po = new SvcOrderItemPO();
                BeanUtils.copyProperties(item, po);
                po.insertOrUpdate();
            }
        }

        // 更新预估备件性质
        List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(SVCServiceRequestVO.getiD());
        if (spaList != null && spaList.size() > 0) {
            for (SVCServiceRequestSpaDTO spa : spaList) {
                Boolean isExist = false;
                for (SvcBusConfigPO configItem : SVCBusConfigList) {
                    if (configItem.getvRepClsCode() != null
                            && configItem.getvRepClsCode().equals(spa.getvKind())) {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist) {
                    spa.setvKind(vDefaultKind);
                    spa.setvKindName(vDefaultKindName);
                }

                spa.setvWorkProp(vSvcKind);
                SvcOrderSpaPO spapo = new SvcOrderSpaPO();
                BeanUtils.copyProperties(spa, spapo);
                spapo.updateById();
            }
        }

        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        map.put("sVCServiceRequestItemVO", itemList);
        map.put("sVCServiceRequestSpaVO", spaList);
        map.put("sREMessage", "009");


        return map;
    }

    // 委托书搜索帮助
    @Override
    public List<SVCSvcKindSHVODTO> sVCKindSH0101() {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto db1 = new DbUnionCommonDto();
        db1.setQueryConditions(" a.NCusGroupID ", 0, userInfor.getnCustGroupId());
        String ndid = userInfor.getnDID();
        List<SVCSvcKindSHVODTO> listInsure = svc0101Mapper.svcSvcKindSHVOsvc0101(db1);
        return listInsure;
    }

    // 会员委托书类型
    @Override
    public List<Map> clbWtsSearch() {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto db1 = new DbUnionCommonDto();
        db1.setQueryConditions(" a.NCusGroupID ", 0, userInfor.getnCustGroupId());
        String ndid = userInfor.getnDID();
        if ("75822760-0000-0000-0000-000000000000".equals(ndid)) {
            db1.setQueryConditions("a.VSvcCls", 1, "J");
            db1.setQueryConditions("a.VSvcCls", 1, "P");
            db1.setQueryConditions("a.VSvcCls", 1, "8");
            db1.setQueryConditions("a.VSvcCls", 1, "7");
        } else {
            db1.setQueryConditions("a.VSvcCls", 1, "J");
            db1.setQueryConditions("a.VSvcCls", 1, "P");
            db1.setQueryConditions("a.VSvcCls", 1, "8");
            db1.setQueryConditions("a.VSvcCls", 1, "7");
            db1.setQueryConditions("a.VSvcCls", 1, "Y");
        }
        db1.setQueryConditions("a.vRepClsCode", 1, "3");
        List<Map> listInsure = svc0101Mapper.clbWtsSearch(db1);
        return listInsure;
    }

    // 委托书搜索帮助
    @Override
    public List<SVCSvcKindSHVODTO> sVCKindSH0203() {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto db1 = new DbUnionCommonDto();
        db1.setQueryConditions(" a.NCusGroupID ", 0, userInfor.getnCustGroupId());
        String ndid = userInfor.getnDID();
        if (!"75822760-0000-0000-0000-000000000000".equals(ndid)) {
            db1.setQueryConditions("a.VSvcCls", 1, "Y");
        }
        List<SVCSvcKindSHVODTO> listInsure = svc0101Mapper.svcSvcKindSHVOsvc0101(db1);
        return listInsure;
    }

    // 获取修改参数和权限
    @Override
    public Map<String, Object> getpararight(SvcServiceRequestViewDTO SVCServiceRequestVO) {

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        Map<String, Object> map = new HashMap<>();

        String NBID = userInfor.getnDID();

        // 取人员权限
        // ALTERITEMNAME    权限-允许修改项目名称 --CChangeVItemName
        // CP     权限-允许修改项目工时 --CChangeNManhaur
        // CQ     权限-允许修改项目工时费 --CChangeNManhaurFee
        // AlterItemKind 权限-允许修改项目性质 --AlterItemKind

        GetRightByPersonVO getRightByPersonVO = new GetRightByPersonVO();
        getRightByPersonVO.setvLogin(userInfor.getvLogin());
        getRightByPersonVO.setvRight("ALTERITEMNAME");
        RestResultResponse result1 =
                iInvokeService.getRightByPerson(userInfor.getnDID(), getRightByPersonVO);
        Map CChangeVItemNameSDO = (Map) result1.getData();
        String CChangeVItemName = "";
        if (CChangeVItemNameSDO != null) {
            CChangeVItemName = "1";
        }

        getRightByPersonVO.setvRight("CP");
        RestResultResponse result2 =
                iInvokeService.getRightByPerson(userInfor.getnDID(), getRightByPersonVO);
        Map CChangeNManhaurSDO = (Map) result2.getData();
        String CChangeNManhaur = "";
        if (CChangeNManhaurSDO != null) {
            CChangeNManhaur = "1";
        }

        getRightByPersonVO.setvRight("CQ");
        RestResultResponse result3 =
                iInvokeService.getRightByPerson(userInfor.getnDID(), getRightByPersonVO);
        Map CChangeNManhaurFeeSDO = (Map) result3.getData();
        String CChangeNManhaurFee = "";
        if (CChangeNManhaurFeeSDO != null) {
            CChangeNManhaurFee = "1";
        }

        getRightByPersonVO.setvRight("AlterItemKind");
        RestResultResponse result4 =
                iInvokeService.getRightByPerson(userInfor.getnDID(), getRightByPersonVO);
        Map AlterItemKindSDO = (Map) result4.getData();
        String AlterItemKind = "";
        if (AlterItemKindSDO != null) {
            AlterItemKind = "1";
        }

        getRightByPersonVO.setvRight("DeleteSvcItem");
        RestResultResponse result5 =
                iInvokeService.getRightByPerson(userInfor.getnDID(), getRightByPersonVO);
        Map DeleteSvcItemSDO = (Map) result5.getData();
        String DeleteSvcItem = "";
        if (AlterItemKindSDO != null) {
            DeleteSvcItem = "1";
        }

        // 取参数
        // LCYGS  允许修改常用项目工时   --CChangeCNManhaurFee
        // LCYGSF 允许修改常用项目工时费 --CChangeCNManhaur
        String CChangeCNManhaurFee = stmCommonService.GetParameters("LCYGS", NBID, "SVC");
        String CChangeCNManhaur = stmCommonService.GetParameters("LCYGSF", NBID, "SVC");
        // 工时统计使用派工日期
        String LTJSYPG = stmCommonService.GetParameters("LTJSYPG", NBID, "SVC");

        // 工时定额
        SvcStandardrationPO SVCStandardration = new SvcStandardrationPO();
        QueryWrapper<SvcStandardrationPO> querGS = new QueryWrapper<>();
        querGS.eq("id", SVCServiceRequestVO.getnStdID());
        querGS.eq("ndid", userInfor.getnDID());
        List<SvcStandardrationPO> listGS = SVCStandardration.selectList(querGS);

        if (listGS != null && listGS.size() > 0) {
            BeanUtils.copyProperties(listGS.get(0), SVCStandardration);
        }

        map.put("cChangeVItemName", CChangeVItemName);
        map.put("cChangeNManhaur", CChangeNManhaur);
        map.put("cChangeNManhaurFee", CChangeNManhaurFee);
        map.put("cChangeCNManhaurFee", CChangeCNManhaurFee);
        map.put("cChangeCNManhaur", CChangeCNManhaur);
        map.put("lTJSYPG", LTJSYPG);
        map.put("deleteSvcItem", DeleteSvcItem);

        // 7获取服务业务配置 是否免费
        String isFree = "0";

        DbUnionCommonDto searchEntity5 = new DbUnionCommonDto();
        searchEntity5.setQueryConditions("a.NCusGroupID", 0, userInfor.getnCustGroupId());
        searchEntity5.setQueryConditions("a.VSvcCls", 0, SVCServiceRequestVO.getvSvcKind());
        List<SvcBusConfigPO> busList = sVCBusConfigMapper.getSvcBusConfigDTOList(searchEntity5);
        if (busList != null && busList.size() > 0) {
            String VSystemClsProp = busList.get(0).getvSystemClsProp();
            if ("0".equals(VSystemClsProp)) {
                isFree = "1";
            }
        }
        // 重新获取委托书SDO
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getiD())) {
            throw new DmsBizException(201, "未获取到委托书ID");
        }
        SVCVO.setQueryConditions("a.id", 0, SVCServiceRequestVO.getiD());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        if (list != null && list.size() > 0) {
            SVCServiceRequestVO = list.get(0);
        }

        // 收费委托书 and 操作授予【修改维修项目性质】 and 包工方式是【不包】下可修改项目性质
        if ("0".equals(isFree)
                && "1".equals(AlterItemKind)
                && "00".equals(SVCServiceRequestVO.getvContractMode())) {
            AlterItemKind = "1";
        } else {
            AlterItemKind = "0";
        }
        map.put("alterItemKind", AlterItemKind);

        map.put("sVCStandardration", SVCStandardration);

        return map;
    }

    List<CRMInsuranceVODTO> getCRMInsuranceVO(String ndid, String vvin) {
        DbUnionCommonDto db1 = new DbUnionCommonDto();
        db1.setQueryConditions("a.NDID", 0, ndid);
        db1.setQueryConditions("a.VVin", 0, vvin);
        List<CRMInsuranceVODTO> listInsure = cRMInsuranceVOMapper.cRMInsuranceVO(db1);
        return listInsure;
    }

    // 校验三包
    @Override
    public Map<String, Object> checkGuarantee(SVCServiceRequestVO SVCServiceRequest)
            throws Exception {
        Map<String, Object> map = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        // 是否符合三包
        String vIsInGuarantee = "0";
        // 取系统参数
        // 三包执行日期
        String vGuaranteeStardDate =
                stmCommonService.GetParameters("GuaranteeStardDate", SVCServiceRequest.getnBID(), "SVC");
        LocalDateTime dGuaranteeStardDate = LocalDateTime.now();
        if (!DotNetToJavaStringHelper.isNullOrEmpty(vGuaranteeStardDate)) {
            dGuaranteeStardDate = LocalDateTimeUtils.stringToLocalDate(vGuaranteeStardDate);
        }

        // 三包有效期（时间）
        String vGuaranteeValidTime =
                stmCommonService.GetParameters("GuaranteeValidTime", SVCServiceRequest.getnBID(), "SVC");
        int nGuaranteeValidTime = 0;
        nGuaranteeValidTime = Integer.parseInt(vGuaranteeValidTime);

        // 三包有效期（里程）
        String vGuaranteeValidMileage =
                stmCommonService.GetParameters("GuaranteeValidMileage", SVCServiceRequest.getnBID(), "SVC");
        BigDecimal nGuaranteeValidMileage = new BigDecimal(0);
        nGuaranteeValidMileage = new BigDecimal(vGuaranteeValidMileage);

        // 购车日期
        LocalDateTime dBuy = SVCServiceRequest.getdBuy();
        /************************************Start***************************************/
        //20201116 逄海修改 ，如果购车日期为空，将购车日期设为默认日期（1900-01-01）
        if (null == dBuy) {
            dBuy = LocalDateTimeUtils.stringToLocalDateTime("1900-01-01 00:00:00");
        }
        /************************************End***************************************/
        Duration duration = Duration.between(now, dBuy);
        long days = duration.toDays(); // 相差的天数
        BigDecimal nDayPart = new BigDecimal(days);
        BigDecimal nMileage = new BigDecimal(0);
        if(SVCServiceRequest.getnMileage() != null)
        {
            // 行驶里程
            nMileage = SVCServiceRequest.getnMileage();
        }
        // 购车日期>三包执行日期 and 购车日期在三包时间内 and 行驶里程在三包里程内
        if (dBuy.compareTo(dGuaranteeStardDate) > 0
                && now.compareTo(dBuy.plusMonths(nGuaranteeValidTime)) <= 0
                && nMileage.compareTo(nGuaranteeValidMileage) <= 0) {
            vIsInGuarantee = "1";
        }
        map.put("isInGuarantee", vIsInGuarantee);
        return map;
    }

    // 校验在修委托书
    @Override
    public Map<String, Object> checkRepairingBill(Map<String, String> UserCustomDynamicData) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        String isHasRepairing = "0";
        String vVin = UserCustomDynamicData.get("vVin");
        String vBillNO = UserCustomDynamicData.get("vBillNO");

        DbUnionCommonDto SVCServiceRequestQAView = new DbUnionCommonDto();
        SVCServiceRequestQAView.setQueryConditions("a.NDID", 0, userInfor.getnDID());
        SVCServiceRequestQAView.setQueryConditions("a.VVin", 0, vVin);
        SVCServiceRequestQAView.setQueryConditions("a.VRepairStatus", 0, "00");
        SVCServiceRequestQAView.setQueryConditions("a.CDelete", 0, "0");
        SVCServiceRequestQAView.setQueryConditions("a.VBillNO", 1, vBillNO);
        List<SVCServiceRequestQAVO> SVCServiceRequestQAList =
                sVCServiceRequestQAVOMapper.sVCServiceRequestQAVO(SVCServiceRequestQAView);
        if (SVCServiceRequestQAList != null && SVCServiceRequestQAList.size() > 0) {
            isHasRepairing = "1";
        }
        map.put("isHasRepairing", isHasRepairing);
        return map;
    }

    // 新保
    @Transactional
    @Override
    public Map<String, Object> savefreemt(SVC0101SaveVO sVC0101SaveVO) {
        LocalDateTime now = LocalDateTime.now();
        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SvcServiceRequestViewDTO = sVC0101SaveVO.getsVCServiceRequestVO();
        SvcOrderPO SVCServiceRequestVO = new SvcOrderPO();
        QueryWrapper<SvcOrderPO> svcquery = new QueryWrapper<>();
        svcquery.eq("ID", SvcServiceRequestViewDTO.getiD());
        List<SvcOrderPO> list = SVCServiceRequestVO.selectList(svcquery);
        if (list != null && list.size() > 0) {
            BeanUtils.copyProperties(list.get(0), SVCServiceRequestVO);
        } else {
            message.putMessage("SVCMessage", "125", new String[]{"委托书读取错误，请关闭当前界面重新进入！"});
            map.put("err", message);
            return map;
        }
        List<SVCFreeMTItfDataCM> selects = sVC0101SaveVO.getsVCFreeMTItfDataCM();
        if (selects != null && selects.size() > 0) {
            SVCMaintainSuitViewDTO SVCMaintainSuitVO = new SVCMaintainSuitViewDTO();
            for (SVCFreeMTItfDataCM SVCFreeMTItfDataCM : selects) {
                // 项目
                if (SVCFreeMTItfDataCM != null
                        && SVCMaintainSuitVO != null
                        && "0".equals(SVCFreeMTItfDataCM.getvType())) {
                    // 校验是否存在重复项目
                    if (SelfIsExist(
                            "SVCServiceRequestItemVO",
                            SVCServiceRequestVO.getiD(),
                            "VItem",
                            SVCFreeMTItfDataCM.getvItem())) {
                        message.putMessage(
                                "SVCMessage",
                                "006",
                                new String[]{"项目", SVCFreeMTItfDataCM.getvItem()}); // {0}{1}已经存在!
                        map.put("err", message);
                        return map;
                    } else if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(SVCFreeMTItfDataCM.getvItem())) {
                        // 套餐项目信息 SVCMaintainSuitItemVO-->SVCMaintainSuitItemDTO
//                        DbUnionCommonDto searchEntity = new DbUnionCommonDto();
//                        searchEntity.setQueryConditions("a.NMainID", 0, SVCMaintainSuitVO.getiD());
//                        searchEntity.setQueryConditions("b.vitem", 0, SVCFreeMTItfDataCM.getvItem());
//                        List<SVCMaintainSuitItemDTO> SVCMaintainSuitItemList =
//                                sVCMaintainSuitItemDTOMapper.getSVCMaintainSuitItemList(searchEntity);
                        if (SVCFreeMTItfDataCM != null) {
                            SvcOrderItemPO SVCServiceRequestItemVO = new SvcOrderItemPO();

                            SVCServiceRequestItemVO.setnMainID(SVCServiceRequestVO.getiD());
//                            SVCServiceRequestItemVO.setnItemID(SVCMaintainSuitItemList.get(0).getnItemID());
                            SVCServiceRequestItemVO.setvItem(SVCFreeMTItfDataCM.getvItem());
                            SVCServiceRequestItemVO.setvItemName(SVCFreeMTItfDataCM.getvItemName());
                            SVCServiceRequestItemVO.setvKind("1");
                            SVCServiceRequestItemVO.setnManhaurFee(
                                    SVCFreeMTItfDataCM.getnPrice());
                            SVCServiceRequestItemVO.setnManhaur(SVCFreeMTItfDataCM.getnSpaQty());
//                            SVCServiceRequestItemVO.setvAdditionalDesc(
//                                    SVCMaintainSuitItemList.get(0).getvAdditionalDesc());
                            SVCServiceRequestItemVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestItemVO.setvItemProperty("0");
                            SVCServiceRequestItemVO.setnSVCAdviserID(SVCServiceRequestVO.getnSVCAdviserID());
                            SVCServiceRequestItemVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
//                            SVCServiceRequestItemVO.setnRepairDuration(
//                                    SVCMaintainSuitItemList.get(0).getnRepairDuration());
                            String spe = "";

                            if (StringUtils.isNullOrEmpty(spe)) {
                                spe = "0";
                            }
                            SVCServiceRequestItemVO.setcSpecialStation(Integer.parseInt(spe));
                            SVCServiceRequestItemVO.setnSuitID("00000000-0000-0000-0000-000000000000");
                            //明新提的jiar说新保养不要追加标识
                            SVCServiceRequestItemVO.setcAppendItem(0);
                            SVCServiceRequestItemVO.insertOrUpdate();
                        }
                    }
                }
                // 备件
                else if (SVCFreeMTItfDataCM != null && SVCMaintainSuitVO != null && "1".equals(SVCFreeMTItfDataCM.getvType())) {

                    // 校验是否存在重复备件
                    if (SelfIsExist(
                            "SVCServiceRequestSpaVO",
                            SVCServiceRequestVO.getiD(),
                            "vspa-|vMoudle",
                            SVCFreeMTItfDataCM.getvItem() + "@" + "SPA")) {
                        message.putMessage(
                                "SVCMessage",
                                "006",
                                new String[]{"备件", SVCFreeMTItfDataCM.getvItem()}); // {0}{1}已经存在!
                        map.put("err", message);
                        return map;
                    } else {
                        DMSLoginInfoDto userInfor =
                                ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
                                    SvcOrderSpaPO SVCServiceRequestSpa = new SvcOrderSpaPO();
                                    SVCServiceRequestSpa.setnMainID(SVCServiceRequestVO.getiD());
                                    SVCServiceRequestSpa.setvModule("SPA");
                                    SVCServiceRequestSpa.setnQty(SVCFreeMTItfDataCM.getnSpaQty());
                                    SVCServiceRequestSpa.setnDID(SVCServiceRequestVO.getnDID());
                                    SVCServiceRequestSpa.setvSpa(SVCFreeMTItfDataCM.getvItem());
                                    SVCServiceRequestSpa.setvSpaAlias(SVCFreeMTItfDataCM.getvItemName());
                                    SVCServiceRequestSpa.setvKind("1");
                                    SVCServiceRequestSpa.setnPrice(SVCFreeMTItfDataCM.getnPrice());
                                    SVCServiceRequestSpa.setdOut(now);
                                    SVCServiceRequestSpa.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                                    SVCServiceRequestSpa.setnSuitID("00000000-0000-0000-0000-000000000000");
                                    SVCServiceRequestSpa.setvWH(SVCFreeMTItfDataCM.getvWH());
                                    SVCServiceRequestSpa.setvChannel("1");
                                    SVCServiceRequestSpa.insertOrUpdate();
                                    SVCServiceRequestSpa = null;

                    }
                }
            }
            if (SVCMaintainSuitVO != null) {
                SVCServiceRequestVO.setnStdID(SVCMaintainSuitVO.getnStdID());
                SVCServiceRequestVO.setcFreeMaintain(1);
                SVCServiceRequestVO.insertOrUpdate();
            }

            message.putMessage("SREMessage", "009");
            map.put("infor", message);
            map.put("iSFreeMtSave", "1");
        }
        return map;
    }

    // 打开建议修理页面
    @Override
    public Map<String, Object> turnsugitem(SvcServiceRequestViewDTO svcServiceRequestVO) {
        Map<String, Object> map = new HashMap<>();
        // TurnSugItemBeginSelf
        SvcServiceRequestViewDTO SVCServiceRequestVO = svcServiceRequestVO;
        // 获取建议项目
        List<SVCServiceRequestSugeestMitVO> sugItemList =
                svc0101_04Service.SelfGetSugItemByMainID(
                        SVCServiceRequestVO.getiD(), SVCServiceRequestVO.getvVin(), 0);
        map.put("sVCServiceRequestSugeestMitVO", sugItemList);
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        return map;
    }

    // 查询建议项目
    @Override
    public Map<String, Object> querysugitem(SVCproposeditemsVO sVCproposeditemsVO) {

        Map<String, Object> map = new HashMap<>();

        String id = sVCproposeditemsVO.getSvcID();
        String vvin = sVCproposeditemsVO.getVvin();
        int isHasHistory = sVCproposeditemsVO.getIsHasHistory();

        // 获取建议项目
        List<SVCServiceRequestSugeestMitVO> sugItemList =
                svc0101_04Service.SelfGetSugItemByMainID(id, vvin, isHasHistory);
        map.put("sVCServiceRequestSugeestMitVO", sugItemList);
        return map;
    }

    @Override
    public QueryEnterMainOut queryEnterMain() {
        QueryEnterMainOut out = new QueryEnterMainOut();
        DMSLoginInfoDto UserInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        LocalDateTime now = LocalDateTime.now();

        SVCGetQuerySvcEnterPR SVCGetQuerySvcEnterPR = new SVCGetQuerySvcEnterPR();
        SVCGetQuerySvcEnterPR.setdEnterBegin_P(now.plusDays((long) -now.getDayOfMonth() + 1));
        SVCGetQuerySvcEnterPR.setdEnterEnd_P(now);
        out.setsVCGetQuerySvcEnterPR(SVCGetQuerySvcEnterPR);
        return out;
    }

    @Override
    public QueryEnterMainOut queryEnterView() {
        QueryEnterMainOut out = new QueryEnterMainOut();
        DMSLoginInfoDto UserInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        LocalDateTime now = LocalDateTime.now();
        DbUnionCommonDto view = new DbUnionCommonDto();
        view.setQueryConditions("a.userID", 0, UserInfor.getiD());
        List<UserRolePO> RoleSDOList = userRoleMapper.userRolePO(view);
        String VRole = "";
        if (RoleSDOList != null && RoleSDOList.size() > 0) {
            UserRolePO RoleSDO = RoleSDOList.get(0);
            VRole = RoleSDO.getvRole();
        }

        SVCGetQuerySvcEnterPR SVCGetQuerySvcEnterPR = new SVCGetQuerySvcEnterPR();
        SVCGetQuerySvcEnterPR.setdEnterBegin_P(now.plusDays((long) -now.getDayOfMonth() + 1));
        SVCGetQuerySvcEnterPR.setdEnterEnd_P(now);
        SVCGetQuerySvcEnterPR.setvRole_P(VRole);

        String TableName = "";
        if ("ADVISER".equals(VRole)) {
            TableName = "ADVISERSVCGetQuerySvcEnterPRTable";
        } else {
            TableName = "SVCGetQuerySvcEnterPRTable";
        }
        SVCGetQuerySvcEnterPR.setTableName(TableName);
        out.setsVCGetQuerySvcEnterPR(SVCGetQuerySvcEnterPR);
        return out;
    }

    // 浏览屏获取参数
    @Override
    public Map<String, Object> getviewloadpara() {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto UserInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        String LQTPL = stmCommonService.GetParameters("LQTPL", UserInfor.getnDID(), "SVC");
        map.put("lQTPL", LQTPL);

        CheckUserRightVO vo = new CheckUserRightVO();
        vo.setNdid(UserInfor.getnDID());
        vo.setUserID(UserInfor.getiD());
        vo.setvRight("DI");
        Map<String, Object> str = iInvokeService.checkuserright(UserInfor.getnDID(), vo);
        Map<String, String> res = (Map<String, String>) str.get("data");
        Integer returnData = Integer.valueOf(res.get("isEXCE"));
        if (returnData == 0) {

            map.put("changeKind", "0");
        } else {
            map.put("changeKind", "1");
        }

        return map;
    }

    // 获取数据源PDI选车给DMS
    @Override
    public RestResultResponse getsalepdifordms(SaleCMPDI saleCMPDI) {

        RestResultResponse res = new RestResultResponse();
        String vbar = saleCMPDI.getPdi();
        DealerPO dear = new DealerPO();
        QueryWrapper<DealerPO> dearQuery = new QueryWrapper();
        dearQuery.eq("VSaleCode", vbar);
        List<DealerPO> dearQ = dear.selectList(dearQuery);
        if (dearQ != null && dearQ.size() > 0) {
            String ndid = dearQ.get(0).getiD();
            if ("1".equals(saleCMPDI.getvSvcKind())) {
                // 索赔类的调用另一个接口
                Map<String, Object> data = ssalFeignClient.getpsvc0101_03(ndid, saleCMPDI);
                Map<String, Object> mapdata = (Map<String, Object>) data.get("data");
                Map map = (Map) mapdata.get("dto");
                Gson gson = new Gson();
                SVC0101_03DTO svc03dto = gson.fromJson(gson.toJson(map), SVC0101_03DTO.class);
                res = RestResultResponseUtils.rest(svc03dto);

            } else {

                if ("8".equals(saleCMPDI.getvSvcKind())) {
                    saleCMPDI.setvSvcFrom("库存,车辆档案");
                }

                res = ssalFeignClient.getsalepdifordms(ndid, saleCMPDI);
            }
        }
        return res;
    }

    // 升级编号搜索帮助
    @Override
    public Map<String, Object> actno(Map<String, String> para) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto UserInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("a.vRecallCode", 0, para.get("vRecallCode"));
// ==============================================召回、行动搜索帮助值加条件区分 于炳森 2021-3-01 ==============================================

        if (para.get("vSvcKind") != null && !StringUtils.isNullOrEmpty(para.get("vSvcKind"))) {
            if ("Z".equals(para.get("vSvcKind"))) {
                dbUnionCommonDto.setQueryConditions("a.vType", 0, "1");
            } else if ("S".equals(para.get("vSvcKind"))) {
                dbUnionCommonDto.setQueryConditions("a.vType", 1, "1");
            }
        }

// ==============================================召回、行动搜索帮助值加条件区分 于炳森 2021-3-01 =============================================
        List<CheckRecallDTO> list = svc0101Mapper.getRecallSearchHelp(para.get("vvin"), UserInfor.getnDID(), dbUnionCommonDto);
        map.put("aCtNo", list);
        return map;
    }

    @Autowired
    RabbitMqUtils rabbitMqController;

    // 委托书保存
    @Transactional
    @Override
    public Map<String, Object> save(SVC0101SaveVO sVC0101SaveVO) throws Exception {

        Map<String, Object> map = new HashMap<>();
        // 保存委托书前 检查 校验

        // 专用工具
        List<SVCServiceRequestToolVO> sVCServiceRequestToolVO =
                sVC0101SaveVO.getsVCServiceRequestToolVO();
        // 建议维修项目 tt_svc_order_sugeest_mit
        List<SVCServiceRequestSugeestMitVO> sVCServiceRequestSugeestMitVO =
                sVC0101SaveVO.getsVCServiceRequestSugeestMitVO();
        // 预估备件 tt_svc_order_spa
        List<SVCServiceRequestSpaDTO> sVCServiceRequestSpaVO =
                sVC0101SaveVO.getsVCServiceRequestSpaVO();

        SvcServiceRequestViewDTO SVCServiceRequestVO = sVC0101SaveVO.getsVCServiceRequestVO();
        // 总被覆盖，提前获取
        String vCusAdressDetail = SVCServiceRequestVO.getvCusAddrDetail();
        String vCusAdress = SVCServiceRequestVO.getvCusAddr();
        // 保存委托书
        // 1 将模型中委托书信息 拷贝至委托书实体中
        // 2 保存成功后将实体中的信息返回模型给前端 注意版本号
        // 3 委托书保存时 委托书上的客户信息 分离到2张表上了，故 子表存在需要语句更新的情况
        // 4 步骤二的操作需要从数据库中查询，因为此保存不是单表保存了
        // 5 保存成功后上传润林
        String svcid = UUID.randomUUID().toString();
        String getID = SVCServiceRequestVO.getiD();
        // 如果是新建委托书，生成新的委托书ID，保存客户档案时要用
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        String IsChageRepairing = sVC0101SaveVO.getIsChageRepairing();
        String IsShowSeccessMsg = sVC0101SaveVO.getIsShowSeccessMsg();

        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime dProd = SVCServiceRequestVO.getdProd();
//        if (dProd == null) {
//            dProd = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
//        }
//        LocalDateTime dBuy = SVCServiceRequestVO.getdBuy();
//        if (dBuy == null) {
//            dBuy = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
//        }
//        LocalDateTime dLicense = SVCServiceRequestVO.getdLicense();
//        if (dLicense == null) {
//            dLicense = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
//        }
        LocalDateTime dEnter = SVCServiceRequestVO.getdEnter();
        String enterstr = LocalDateTimeUtils.localDateTimeToString(dEnter, "yyyy-MM-dd");
        enterstr = enterstr.substring(0, 10) + " 00:00:00";
//        LocalDateTime dEnterbj = LocalDateTimeUtils.stringToLocalDateTime(enterstr);
        LocalDateTime dPickUp = SVCServiceRequestVO.getdPickUp();
        if (dPickUp == null) {
            dPickUp = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        }
        LocalDateTime dEstimateRepair = SVCServiceRequestVO.getdEstimateRepair();
        if (dEstimateRepair == null) {
            dEstimateRepair = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        }
        LocalDateTime dPromiseFinish = SVCServiceRequestVO.getdPromiseFinish();
        if (dPromiseFinish == null) {
            dPromiseFinish = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        }
//        String vLicenseTag = SVCServiceRequestVO.getvLicenseTag();
//
//        LocalDate dBuy_LD = dBuy.toLocalDate();
//        LocalDate dProd_LD = dProd.toLocalDate();
//        LocalDate dLicense_LD = dLicense.toLocalDate();
//        LocalDate dEnterbj_LD = dEnterbj.toLocalDate();

        // 是否上传首保卡号
//        Boolean IsUploadFirstMtNO = false;

        map.put("isSaveSVC", "0");
        // 校验

//        // modi by xh at 20170628 加一个简单的底盘号校验，真正的校验在车辆档案，这个就是防止为空
//        String vVin = SVCServiceRequestVO.getvVin();
//        if ((!StringUtils.isNullOrEmpty(vVin)) && vVin.length() < 17) {
//            message.putMessage("CRMMessage", "002", new String[]{"15"});
//            map.put("err", message);
//            return map;
//        }
        if ((!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCus()))
                && SVCServiceRequestVO.getvCus().contains("*")) {
            // [客户代码]输入不正确，不可为*号!
            message.putMessage("SVCMessage", "069");
            map.put("err", message);
            return map;
        }

        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCusMobile())
                && StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCusTel())) {
            // 客户移动电话和客户电话不可同时为空！
            message.putMessage("SVCMessage", "191");
            map.put("err", message);
            return map;
        }

        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvLkMobile())
                && StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvLkTel())) {
            // 联系人移动电话和联系人电话不可同时为空！
            message.putMessage("SVCMessage", "192");
            map.put("err", message);
            return map;
        }

//        if (dBuy_LD.isBefore(dProd_LD)) {
//            // 购车日期不可小于生产日期!
//            message.putMessage("SVCMessage", "051", new String[]{"销售日期", "生产日期"});
//            map.put("err", message);
//            return map;
//        }

//        if (dBuy_LD.isAfter(dLicense_LD)) {
//            // 购车日期不可小于生产日期!
//            message.putMessage("SVCMessage", "051", new String[]{"发牌日期", "销售日期"});
//            map.put("err", message);
//            return map;
//        }
        //"开机日期", "生产日期"比较去掉
//        if (dLicense_LD.isBefore(dProd_LD)) {
//            // 发牌日期不可小于生产日期!
//            message.putMessage("SVCMessage", "051", new String[]{"开机日期", "生产日期"});
//            map.put("err", message);
//            return map;
//        }

//        if (dBuy_LD.isAfter(dEnterbj_LD)) {
//            // 送修日期不可小于购车日期!
//            message.putMessage("SVCMessage", "051", new String[]{"送修日期", "销售日期"});
//            map.put("err", message);
//            return map;
//        }

        if (dEstimateRepair.isBefore(dEnter)) {
            // 预计维修时间不可小于送修日期!
            message.putMessage("SVCMessage", "051", new String[]{"预计维修时间", "送修日期"});
            map.put("err", message);
            return map;
        }

        if (dEstimateRepair.isBefore(dPickUp)) {
            // 预计维修时间不可小于接车时间!
            message.putMessage("SVCMessage", "051", new String[]{"预计维修时间", "接车时间"});
            map.put("err", message);
            return map;
        }

        if (dPromiseFinish.isBefore(dEstimateRepair)) {
            // 约定交车时间不可小于预计维修时间!
            message.putMessage("SVCMessage", "051", new String[]{"约定交车时间", "预计维修时间"});
            map.put("err", message);
            return map;
        }

//        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getiD())
//                && "1".equals(SVCServiceRequestVO.getvSvcKind())) {
//            Duration dateDiffer =
//                    Duration.between(
//                            SVCServiceRequestVO.getdEnter(), SVCServiceRequestVO.getdPromiseFinish());
//            long hours = dateDiffer.toHours(); // 相差的小时数
//            BigDecimal hoursss = new BigDecimal(hours);
//            BigDecimal b24 = BigDecimal.valueOf(24);
//            BigDecimal days = hoursss.divide(b24, 0, BigDecimal.ROUND_UP);
//            BigDecimal fire = BigDecimal.valueOf(0.5);
//        }
        
        // 校验其他免费类保养取消勾选
        if ((!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getiD()))
                && "2".equals(SVCServiceRequestVO.getvSvcKind())) {
            Boolean change = false;

            SvcOrderPO po = new SvcOrderPO();
            QueryWrapper<SvcOrderPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("vbillno", SVCServiceRequestVO.getvBillNO());
            queryWrapper.eq("ndid", userInfo.getnDID());
            List<SvcOrderPO> list1 = po.selectList(queryWrapper);

            if (list1 != null && list1.size() > 0) {
                if (list1.get(0).getSwglby() != null
                        && !list1.get(0).getSwglby().equals(SVCServiceRequestVO.getSwglby())) {
                    change = true;
                }
            }

            if ((null == SVCServiceRequestVO.getSwglby() || SVCServiceRequestVO.getSwglby() == 0) && change) {

                DbUnionCommonDto view = new DbUnionCommonDto();
                view.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
                view.setQueryConditions("a.VKind", 0, "3");
                List<SVCServiceRequestItemVODTO> returnlist =
                        svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfo.getnDID(), view, vCusGroupId);

                if (returnlist != null && returnlist.size() > 0) {
                    // 存在对应免费项，删除免费项目且免费备件退库后才能取消标识
                    message.putMessage("SVCMessage", "258");
                    map.put("err", message);
                    return map;
                } else {
                    DbUnionCommonDto preSPAView = new DbUnionCommonDto();

                    preSPAView.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
                    preSPAView.setQueryConditions("a.ndid", 0, userInfo.getnDID());
                    preSPAView.setQueryConditions("a.VKind", 0, "3");
                    List<SVCServiceRequestSpaDTO> spalist =
                            svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(preSPAView);
                    if (spalist != null && spalist.size() > 0) {
                        // 存在对应免费项，删除免费项目且免费备件退库后才能取消标识
                        message.putMessage("SVCMessage", "258");
                        map.put("err", message);
                        return map;
                    } else {
                        DbUnionCommonDto searchEntity2 = new DbUnionCommonDto();
                        searchEntity2.setQueryConditions("b.NCorID", 0, SVCServiceRequestVO.getiD());
                        searchEntity2.setQueryConditions("b.VDrawType", 0, "OWX");
                        searchEntity2.setQueryConditions("a.VKind", 0, "3");
                        searchEntity2.setQueryConditions("a.NImpQty", 2, "0");
                        List<SpaGetDrawDetailForSvcVODTO> drawlist =
                                spaGetDrawDetailForSvcVOMapper.query(searchEntity2);

                        if (drawlist != null && drawlist.size() > 0) {
                            // 存在对应免费项，删除免费项目且免费备件退库后才能取消标识
                            message.putMessage("SVCMessage", "258");
                            map.put("err", message);
                            return map;
                        }
                    }
                }
            } else if (null != SVCServiceRequestVO.getSwglby() && 1 == SVCServiceRequestVO.getSwglby()) {
                String VServiceType = SVCServiceRequestVO.getvServiceType();
                String NMaintain = SVCServiceRequestVO.getnMaintain() + "";
                if (SVCServiceRequestVO.getnMileage().compareTo(BigDecimal.valueOf(1000000)) >= 0) {
                    // 行驶里程大于1000000 不允许保存
                    // 行驶里程不能超过百万公里！
                    // 行驶里程已过百万，不能申报免费保养
                    message.putMessage("CLMMessage", "085");
                    map.put("err", message);
                    return map;
                }
                if (StringUtils.isNullOrEmpty(VServiceType) || StringUtils.isNullOrEmpty(NMaintain)) {
                    // 请填写政策类型和保养次数
                    message.putMessage("SVCMessage", "260");
                    map.put("err", message);
                    return map;
                }

                if (SVCServiceRequestVO.getvCarType() == null
                        || SVCServiceRequestVO.getvCarType().length() == 0) {
                    // 请选择车辆类别
                    message.putMessage("SVCMessage", "261");
                    map.put("err", message);
                    return map;
                }

                DbUnionCommonDto view = new DbUnionCommonDto();
                view.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
                view.setQueryConditions("a.VKind", 0, "2");
                List<SVCServiceRequestItemVODTO> returnlist =
                        svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfo.getnDID(), view, vCusGroupId);

                if (returnlist != null && returnlist.size() > 0) {
                    // 若勾选"其他免费类保养",项目性质或备件出库性质必须为"免费"

                    message.putMessage("SVCMessage", "259");
                    map.put("err", message);
                    return map;
                } else {
                    DbUnionCommonDto preSPAView = new DbUnionCommonDto();

                    preSPAView.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
                    preSPAView.setQueryConditions("a.ndid", 0, userInfo.getnDID());
                    preSPAView.setQueryConditions("a.VKind", 0, "2");
                    List<SVCServiceRequestSpaDTO> spalist =
                            svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(preSPAView);
                    if (spalist != null && spalist.size() > 0) {
                        // 项目性质或备件出库性质存在“新保”，不可取消勾选！
                        message.putMessage("SVCMessage", "259");
                        map.put("err", message);
                        return map;
                    } else {
                        DbUnionCommonDto searchEntity2 = new DbUnionCommonDto();
                        searchEntity2.setQueryConditions("b.NCorID", 0, SVCServiceRequestVO.getiD());
                        searchEntity2.setQueryConditions("b.VDrawType", 0, "OWX");
                        searchEntity2.setQueryConditions("a.VKind", 0, "2");
                        searchEntity2.setQueryConditions("a.NImpQty", 2, "0");
                        List<SpaGetDrawDetailForSvcVODTO> drawlist =
                                spaGetDrawDetailForSvcVOMapper.query(searchEntity2);

                        if (drawlist != null && drawlist.size() > 0) {
                            // 项目性质或备件出库性质存在“新保”，不可取消勾选！
                            message.putMessage("SVCMessage", "259");
                            map.put("err", message);
                            return map;
                        }
                    }
                }
            }
        }


        // 按ID获取客户档案
        SvcOrderCusinfoPO VEHICLE = new SvcOrderCusinfoPO();
        QueryWrapper<SvcOrderCusinfoPO> queryVE = new QueryWrapper<>();
        queryVE.eq("nmainid", SVCServiceRequestVO.getiD());
        queryVE.eq("ndid", SVCServiceRequestVO.getnDID());
        List<SvcOrderCusinfoPO> listve = VEHICLE.selectList(queryVE);

        SvcOrderCusinfoPO CRMCustomer = new SvcOrderCusinfoPO();
        if (listve != null && listve.size() > 0) {
            BeanUtils.copyProperties(listve.get(0), CRMCustomer);
        }

        CRMCustomer.setvCusName(SVCServiceRequestVO.getvCusName());
        CRMCustomer.setvCusMobile(SVCServiceRequestVO.getvCusMobile());
        CRMCustomer.setvCusTel(SVCServiceRequestVO.getvCusTel());
        CRMCustomer.setvClass(SVCServiceRequestVO.getvClass());
        CRMCustomer.setvCusAddr(SVCServiceRequestVO.getvCusAddr());
        CRMCustomer.setvCusEvaClass(SVCServiceRequestVO.getvCusEvaClass());
        //        CRMCustomer.setbRepair(1);
        CRMCustomer.setvConstractTime(SVCServiceRequestVO.getvConstractTime());
        CRMCustomer.setvConstractType(SVCServiceRequestVO.getvConstractType());
        CRMCustomer.setvCus(SVCServiceRequestVO.getvCus());
        CRMCustomer.setnDid(userInfo.getnDID());
        CRMCustomer.setnBid(userInfo.getnDID());

        if (StringUtils.isNullOrEmpty(getID)) {// 新建
            // 校验车主召回信息
            if ("S".equals(SVCServiceRequestVO.getvSvcKind())
                    || "V".equals(SVCServiceRequestVO.getvSvcKind())
                    || "Z".equals(SVCServiceRequestVO.getvSvcKind())) {
                DbUnionCommonDto db1 = new DbUnionCommonDto();
                db1.setQueryConditions("a.NDID", 0, userInfo.getnDID());
                db1.setQueryConditions("a.VVin", 0, SVCServiceRequestVO.getvVin());
                db1.setQueryConditions("a.VRecallCode", 0, SVCServiceRequestVO.getvUpgradeNO());
                List<SvcRecallCusDTO> SVCRecallCusVOList = svcRecallCusMapper.querySVCRecallCusVO(db1);
                if (SVCRecallCusVOList != null && SVCRecallCusVOList.size() > 0) {
                    String vstr = "";
                    String VCusName = SVCRecallCusVOList.get(0).getvCusName();
                    String VTel = SVCRecallCusVOList.get(0).getvTel();
                    String VMobile = SVCRecallCusVOList.get(0).getvMobile();

                    /** 需要解密 暂时不转 */
                    String VCusName1 = "";
                    if (!StringUtils.isNullOrEmpty(VCusName)) {
                        VCusName1 = VCusName;
                    }
                    String VTel1 = "";
                    if (!StringUtils.isNullOrEmpty(VTel)) {
                        VTel1 = VTel;
                    }
                    String VMobile1 = "";
                    if (!StringUtils.isNullOrEmpty(VMobile)) {
                        VMobile1 = VMobile;
                    }

                    if (!StringUtils.isNullOrEmpty(VCusName1)
                            && !VCusName1.equals(SVCServiceRequestVO.getvCusName())) {
                        vstr = "客户名称，";
                    }

                    if (!StringUtils.isNullOrEmpty(VTel1)
                            && !VTel1.equals(SVCServiceRequestVO.getvCusTel())) {
                        vstr = vstr + "固定电话，";
                    }

                    if (!StringUtils.isNullOrEmpty(VMobile1)
                            && !VMobile1.equals(SVCServiceRequestVO.getvCusMobile())) {
                        vstr = vstr + "移动电话，";
                    }

                    if (vstr.length() > 0) {
                        vstr = vstr.substring(0, vstr.length() - 1);
                        message.putMessage("SVCMessage", "235", new String[]{vstr});
                    }
                }
            }
            String vBillNo = "";
            String vSvcKind = SVCServiceRequestVO.getvSvcKind();
            // 获取委托书号
            if (SVCServiceRequestVO.getvBillNO() == null
                    || (SVCServiceRequestVO.getvBillNO() != null
                    && SVCServiceRequestVO.getvBillNO().length() < 3)) {
                LocalDateTime date = LocalDateTime.now();
                vBillNo =
                        fwSystemOrderNoService.getSystemOrderNoYyyyMMdd(
                                "D",
                                "D",
                                userInfo.getnDID(),
                                LocalDateTimeUtils.localDateTimeToString(date, "yyyyMMdd"),
                                "3");

                vBillNo = vBillNo.substring(1, vBillNo.length());
                // 开启迷你店
                String MINI = stmCommonService.GetParameters("MINIQY", userInfo.getnDID(), "SYS");
                if ("1".equals(MINI)) {
                    // 获取网点代码替换到委托书前两位 20200909004
                    String vBranchCode = "";
                    TmBranchMqPO tmBranch = new TmBranchMqPO();
                    tmBranch = tmBranch.selectById(userInfo.getnBID());

                    // 未停用的网点
                    if (tmBranch != null && tmBranch.getcStop() != 1) {
                        vBranchCode = tmBranch.getvBranchCode();
                        vBillNo = vBranchCode + vBillNo.substring(2);
                    }
                }

                vBillNo = userInfo.getvDealer() + "-" + vSvcKind + "-" + vBillNo;
                SVCServiceRequestVO.setvBillNO(vBillNo);
            }
            SVCServiceRequestVO.setcSettle(0);
            SVCServiceRequestVO.setcDelete(0);
            SVCServiceRequestVO.setcPDIS(0);
            SVCServiceRequestVO.setiD(svcid);
            SVCServiceRequestVO.setdOpr(LocalDateTime.now());

            if ("0".equals(SVCServiceRequestVO.getvSvcKind())) {
                SVCServiceRequestVO.setcFirstMT(1);
                SVCServiceRequestVO.setcCLM(0);
            } else if ("1".equals(SVCServiceRequestVO.getvSvcKind())
                    || "G".equals(SVCServiceRequestVO.getvSvcKind())
                    || "S".equals(SVCServiceRequestVO.getvSvcKind())
                    || "V".equals(SVCServiceRequestVO.getvSvcKind())
                    || "Z".equals(SVCServiceRequestVO.getvSvcKind())) {
                SVCServiceRequestVO.setcFirstMT(0);
                SVCServiceRequestVO.setcCLM(1);
            } else {
                SVCServiceRequestVO.setcFirstMT(0);
                SVCServiceRequestVO.setcCLM(0);
            }
//            if(StringUtils.isNullOrEmpty(SVCServiceRequestVO.getcIPad())) {
//                SVCServiceRequestVO.setcIPad(0);
//            }
            if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCus())) {
                SVCServiceRequestVO.setvCus(CRMCustomer.getvCus());
            }
            SVCServiceRequestVO.setnBID(userInfo.getnBID());
            SVCServiceRequestVO.setnDID(userInfo.getnDID());
            SvcOrderPO po = new SvcOrderPO();
            BeanUtils.copyProperties(SVCServiceRequestVO, po);
            //如果在三包期内更新字段 vWarrantyState = 0
            if ("1".equals(SVCServiceRequestVO.getvSvcKind()) && "01".equals(SVCServiceRequestVO.getvClass()) && !"LFV000000WW000000".equals(SVCServiceRequestVO.getvVin())) {
                SVCServiceRequestVO checkSANBAO = new SVCServiceRequestVO();
                checkSANBAO.setnBID(userInfo.getnBID());
                checkSANBAO.setdBuy(SVCServiceRequestVO.getdBuy());
                checkSANBAO.setnMileage(SVCServiceRequestVO.getnMileage());
                Map<String, Object> sanbaoMap = checkGuarantee(checkSANBAO);
                String isInGuarantee = sanbaoMap.get("isInGuarantee") + "";
                if ("1".equals(isInGuarantee)) {
                    po.setvWarrantyState("0");
                }
            }

            // 判断委托单新增或更新标识
            boolean flag = po.insertOrUpdate();

            // 查询该委托书ID用于同步app库数据ID
            SvcOrderPO appOrderPO = new SvcOrderPO();
            QueryWrapper<SvcOrderPO> appOrderWapper = new QueryWrapper<>();
            appOrderWapper.eq("nDID",userInfo.getnDID());
            appOrderWapper.eq("vBillNo",po.getvBillNO());
            appOrderPO = appOrderPO.selectOne(appOrderWapper);
            logger.info("委托书保存同步App库:{}",po.toString());
            po.setiD(appOrderPO.getiD()); // 保持服务库委托书和app库委托书ID一致
            svcToSanyAppService.sendToSanyApp(po);
//            po.setvOrderType("02");

            // 如果委托单新增增加埋点
            logger.info("委托书保存埋点:{}",flag);
            if (flag) {
                logger.info("新增埋点前委托书PO:{}",appOrderPO);
                SvcBuryingPointPO pointPO = new SvcBuryingPointPO();
                pointPO.setvDesc("委托单");
                pointPO.setiD(UUID.randomUUID().toString());
                pointPO.setnDID(userInfo.getnDID());
                pointPO.setnCorID(appOrderPO.getiD());
                if (sVC0101SaveVO.getcIsFromRMS() != null && sVC0101SaveVO.getcIsFromRMS() == 1) {
                    pointPO.setvFrom("01"); // 来源RMS
                }
                pointPO.setvBillType("Svc0101");
                pointPO.insert();
            }
            //创建服务/销售订单
            String useSanyCrm = stmCommonService.GetParameters("useSanyCrm", userInfo.getnDID(), "SVC");
            if (("1").equals(useSanyCrm)) {
                String OBJECT_ID_SRV = "";
                //不是原厂车不创建服务订单
                MdaProductMixPO mixPO = new MdaProductMixPO();
                mixPO.setiD(SVCServiceRequestVO.getnSaleTypeID());
                mixPO = mixPO.selectById();
                if (mixPO != null && !StringUtils.isNullOrEmpty(mixPO.getiD())){
                    if ((1) == (mixPO.getcFactory() != null ? mixPO.getcFactory() : 0)){
                        // 根据ID 查询委托书
                        DbUnionCommonDto view1 = new DbUnionCommonDto();
                        view1.setQueryConditions("a.ID", 0, po.getiD());
                        List<SVCServiceRequestVODTO> svclists = svc0104SvcOrderMapper.sVCServiceRequestVO(view1);
                        if (svclists.size() > 0) {
                            SvcServiceRequestViewDTO svcServiceRequestVO = new SvcServiceRequestViewDTO();
                            BeanUtils.copyProperties(svclists.get(0), svcServiceRequestVO);
                            SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO1 = new SaveSVCServiceRequestSpaVO();
                            saveSVCServiceRequestSpaVO1.setsVCServiceRequestVO(svcServiceRequestVO);
                            saveSVCServiceRequestSpaVO1.setVlkName(SVCServiceRequestVO.getvLkName());
                            saveSVCServiceRequestSpaVO1.setVlkTel(SVCServiceRequestVO.getvLkTel());
                            saveSVCServiceRequestSpaVO1.setVlkMobile(SVCServiceRequestVO.getvLkMobile());
                            //这里貌似只是上传了大修订单过去，没传配件信息
                            OBJECT_ID_SRV = svcToSanyCrmService.upLoadSpaToSanyCrm(saveSVCServiceRequestSpaVO1);
                            po.setvObjectID(OBJECT_ID_SRV);
                        }

                        if ("02".equals(po.getvOrderType())) {
                            SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
                            svcSaleOrderInfoDTO.setZWTS_NO(po.getvBillNO());
                            svcSaleOrderInfoDTO.setZDXC_NO(userInfo.getvDealer());
                            svcSaleOrderInfoDTO.setCUST_NO(po.getvCus());
                            svcSaleOrderInfoDTO.setZZEQUIPMENTNO(po.getvVin());
                            svcSaleOrderInfoDTO.setPMNTTRMS(po.getvZXYX());
                            OBJECT_ID_SRV = OBJECT_ID_SRV + ";" + svcToSanyCrmService.createCRMSaleOrder(svcSaleOrderInfoDTO);
                            po.setvObjectID(OBJECT_ID_SRV);
                        }
                    }else{
                        if ("02".equals(po.getvOrderType())) {
                            SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
                            svcSaleOrderInfoDTO.setZWTS_NO(userInfo.getvDealer() + "-" + po.getvBillNO());
                            svcSaleOrderInfoDTO.setZDXC_NO(userInfo.getvDealer());
                            svcSaleOrderInfoDTO.setCUST_NO(po.getvCus());
                            svcSaleOrderInfoDTO.setZZEQUIPMENTNO(po.getvVin());
                            svcSaleOrderInfoDTO.setPMNTTRMS(po.getvZXYX());
                            OBJECT_ID_SRV = "" + ";" +svcToSanyCrmService.createCRMSaleOrder(svcSaleOrderInfoDTO);

                            po.setvObjectID(OBJECT_ID_SRV);
                        }
                    }
                    po.insertOrUpdate();
                }
            }

            SVCServiceRequestVO.setRecordVersion(po.getRecordVersion());
            SVCServiceRequestVO.setiD(po.getiD());
            // SVCBusConfigVO--->对应SvcBusConfigDTO
            DbUnionCommonDto searchEntity5 = new DbUnionCommonDto();
            // 客户组ID
            searchEntity5.setQueryConditions("a.NCusGroupID", 0, "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74");
            searchEntity5.setQueryConditions("a.VSvcCls", 0, SVCServiceRequestVO.getvSvcKind());
            searchEntity5.setOrderBys("a.vRepClsCode Asc");
            List<SvcBusConfigPO> SVCBusConfigList =
                    sVCBusConfigMapper.getSvcBusConfigDTOList(searchEntity5);
            String vDefaultKind = "";
            String vDefaultKindName = "";
            logger.info("默认性质列表:{}", SVCBusConfigList);
            if (SVCBusConfigList != null && SVCBusConfigList.size() > 0) {
                vDefaultKind = SVCBusConfigList.get(0).getvRepClsCode();
                vDefaultKindName = SVCBusConfigList.get(0).getvRepClsName();
            }


            // 来源预约
            if ("0".equals(SVCServiceRequestVO.getvSvcFrom())) {

                // 更新预约单
                DbUnionCommonDto view = new DbUnionCommonDto();
                view.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getnSvcFromBillID());
                List<SVCBookRegisterVO> SVCBookRegisterList = null;
                if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnSvcFromBillID())) {
                    SVCBookRegisterList = sVCBookRegisterVOMapper.sVCBookRegisterVO(view, userInfo.getnDID());
                }

                if (SVCBookRegisterList != null && SVCBookRegisterList.size() > 0) {
                    SvcBookRegisterPO poyy = new SvcBookRegisterPO();
//                    svc0203Service.sendBookRegister(SVCBookRegisterList.get(0), "4");
//                    String vDealer = this.pucCommonService.getDealerCode(userInfo.getnDID());
//                    UploadOrderDataTask uploadOrderDataTask = new UploadOrderDataTask(userInfo.getnDID(), SVCBookRegisterList.get(0), "4", vDealer);
//                    ExecutorManager.execute(uploadOrderDataTask);

                    QueryWrapper<SvcBookRegisterPO> updatePoyy = new QueryWrapper<>();
                    updatePoyy.eq("id", SVCBookRegisterList.get(0).getiD());
                    List<SvcBookRegisterPO> listPO = poyy.selectList(updatePoyy);
                    BeanUtils.copyProperties(listPO.get(0), poyy);
                    poyy.setvExecuteStatus("02");
                    poyy.setvBillStatus("3");
                    poyy.setdSxrq(SVCServiceRequestVO.getdEnter());
                    poyy.setvWtsbh(SVCServiceRequestVO.getvBillNO());
                    poyy.setIsTransform(1);

                    BookOrderInfoToSanyAppTask bookOrderInfoToSanyAppTask = new BookOrderInfoToSanyAppTask(poyy);
                    ExecutorManager.execute(bookOrderInfoToSanyAppTask);

                    poyy.updateById();

                    SvcWeChatLogPO LogPO = new SvcWeChatLogPO();
                    LogPO.setId(UUID.randomUUID().toString());
                    LogPO.setVType("03");//非取消、失效状态	03
                    LogPO.setDCreate(now);
                    LogPO.setDImp(now);
                    LogPO.setVTrans("SVC0233");
                    LogPO.setVContent("预约进厂：客户已进厂，生成委托书" +
                            po.getvBillNO()
                    );
                    LogPO.setVEntity("tt_svc_book_register");
                    LogPO.setNdid(userInfo.getnDID());
                    LogPO.setNbid(userInfo.getnBID());
                    LogPO.setNOprID(userInfo.getiD());
                    LogPO.setVOpr(userInfo.getvPerson());
                    LogPO.setVOprName(userInfo.getvPersonName());
                    LogPO.setnMainID(poyy.getiD());
                    LogPO.insertOrUpdate();


                    String vteam = SVCBookRegisterList.get(0).getvRepairTeam();
                    String majro = SVCBookRegisterList.get(0).getvBookMajorCode();

                    // 转入预约项目
                    List<YYDTO> bookItemList =
                            svc0101Mapper.bookItem0(SVCServiceRequestVO.getnSvcFromBillID());
                    if (bookItemList != null && bookItemList.size() > 0) {
                        for (YYDTO bookItem : bookItemList) {
                            SVCServiceRequestItemVODTO SVCServiceRequestItemVO = new SVCServiceRequestItemVODTO();
                            SVCServiceRequestItemVO.setnMainID(SVCServiceRequestVO.getiD());
                            SVCServiceRequestItemVO.setvItem(bookItem.getvItem());
                            SVCServiceRequestItemVO.setvItemName(bookItem.getvItemName());
                            if (SVCBookRegisterList.get(0).getvRepairType() != null
                                    && SVCBookRegisterList.get(0)
                                    .getvRepairType()
                                    .equals(SVCServiceRequestVO.getvSvcKind())
                                    && !StringUtils.isNullOrEmpty(bookItem.getvKind())) {
                                SVCServiceRequestItemVO.setvKind(bookItem.getvKind());
                            } else {
                                SVCServiceRequestItemVO.setvKind(vDefaultKind);
                            }
                            SVCServiceRequestItemVO.setnManhaur(bookItem.getnManhaur());
                            SVCServiceRequestItemVO.setnManhaurFee(bookItem.getnManhaurFee());
                            SVCServiceRequestItemVO.setvAdditionalDesc(bookItem.getvAdditionalDesc());
                            SVCServiceRequestItemVO.setvItemProperty(bookItem.getvItemType());
                            SVCServiceRequestItemVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                            SVCServiceRequestItemVO.setnItemID(bookItem.getnItemID());
                            SVCServiceRequestItemVO.setcCommItem(bookItem.getcCommItem());
                            SVCServiceRequestItemVO.setcDownload(bookItem.getcDownload());
                            SVCServiceRequestItemVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestItemVO.setnSVCAdviserID(SVCServiceRequestVO.getnSVCAdviserID());
                            SVCServiceRequestItemVO.setvTeam(bookItem.getvTeam());
                            SVCServiceRequestItemVO.setvMajor(bookItem.getvMajor());
                            SVCServiceRequestItemVO.setvLocation(bookItem.getvStation());
                            SVCServiceRequestItemVO.setcSpecialStation(bookItem.getcSpecialStation());
                            SVCServiceRequestItemVO.setnManhaurDisRate(bookItem.getnManhaurDisRate());
                            SVCServiceRequestItemVO.setvMainPart(bookItem.getvMainPart());
                            SVCServiceRequestItemVO.setvOperateStatus("00");

                            if (!StringUtils.isNullOrEmpty(bookItem.getvTeam())) {
                                DepartmentsPO bmpo = new DepartmentsPO();
                                QueryWrapper<DepartmentsPO> SVCTeamView = new QueryWrapper<>();
                                SVCTeamView.eq("ndid", SVCServiceRequestVO.getnDID());
                                SVCTeamView.eq("vOrg", bookItem.getvTeam());
                                List<DepartmentsPO> teamList = bmpo.selectList(SVCTeamView);

                                if (teamList != null && teamList.size() > 0) {
                                    SVCServiceRequestItemVO.setvRepairProperty(teamList.get(0).getvServiceProperty());
                                }
                            }
                            if (!StringUtils.isNullOrEmpty(vteam)) {
                                SVCServiceRequestItemVO.setvTeam(vteam);
                                SVCServiceRequestItemVO.setvMajor(majro);
                                SVCServiceRequestItemVO.setdTask(LocalDateTime.now());
                            }

                            //
                            SvcOrderItemPO Itempo = new SvcOrderItemPO();
                            BeanUtils.copyProperties(SVCServiceRequestItemVO, Itempo);
                            Itempo.insertOrUpdate();
                            //给小程序同步项目信息
                            svcToSanyAppService.sendItemInfoToSanyApp(Itempo);
                            // 回传版本号
                            SVCServiceRequestItemVO.setRecordVersion(Itempo.getRecordVersion());
                        }
                    }

                    List<YYDTO> bookItemSuitList =
                            svc0101Mapper.bookItem1(SVCServiceRequestVO.getnSvcFromBillID());
                    if (bookItemSuitList != null && bookItemSuitList.size() > 0) {
                        for (YYDTO bookItem : bookItemSuitList) {
                            SVCServiceRequestItemVODTO SVCServiceRequestItemVO = new SVCServiceRequestItemVODTO();
                            SVCServiceRequestItemVO.setnMainID(SVCServiceRequestVO.getiD());
                            SVCServiceRequestItemVO.setvItem(bookItem.getvItem());
                            SVCServiceRequestItemVO.setvItemName(bookItem.getvItemName());
                            if (SVCBookRegisterList.get(0).getvRepairType() != null
                                    && SVCBookRegisterList.get(0)
                                    .getvRepairType()
                                    .equals(SVCServiceRequestVO.getvSvcKind())
                                    && !StringUtils.isNullOrEmpty(bookItem.getvKind())) {
                                SVCServiceRequestItemVO.setvKind(bookItem.getvKind());
                            } else {
                                SVCServiceRequestItemVO.setvKind(vDefaultKind);
                            }
                            SVCServiceRequestItemVO.setnManhaur(bookItem.getnManhaur());
                            SVCServiceRequestItemVO.setnManhaurFee(bookItem.getnManhaurFee());
                            SVCServiceRequestItemVO.setvAdditionalDesc(bookItem.getvAdditionalDesc());
                            SVCServiceRequestItemVO.setvItemProperty(bookItem.getvItemType());
                            SVCServiceRequestItemVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                            SVCServiceRequestItemVO.setnItemID(bookItem.getnItemID());
                            SVCServiceRequestItemVO.setcCommItem(bookItem.getcCommItem());
                            SVCServiceRequestItemVO.setcDownload(bookItem.getcDownload());
                            SVCServiceRequestItemVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestItemVO.setnSVCAdviserID(SVCServiceRequestVO.getnSVCAdviserID());
                            SVCServiceRequestItemVO.setvTeam(bookItem.getvTeam());
                            SVCServiceRequestItemVO.setvMajor(bookItem.getvMajor());
                            SVCServiceRequestItemVO.setvLocation(bookItem.getvStation());
                            SVCServiceRequestItemVO.setcSpecialStation(bookItem.getcSpecialStation());
                            SVCServiceRequestItemVO.setnManhaurDisRate(bookItem.getnManhaurDisRate());
                            SVCServiceRequestItemVO.setvMainPart(bookItem.getvMainPart());
                            if (!StringUtils.isNullOrEmpty(bookItem.getvTeam())) {
                                DepartmentsPO bmpo = new DepartmentsPO();
                                QueryWrapper<DepartmentsPO> SVCTeamView = new QueryWrapper<>();
                                SVCTeamView.eq("ndid", SVCServiceRequestVO.getnDID());
                                SVCTeamView.eq("vorg", bookItem.getvTeam());
                                List<DepartmentsPO> teamList = bmpo.selectList(SVCTeamView);

                                if (teamList != null && teamList.size() > 0) {
                                    SVCServiceRequestItemVO.setvRepairProperty(teamList.get(0).getvServiceProperty());
                                }
                            }
                            //
                            SvcOrderItemPO Itempo = new SvcOrderItemPO();
                            BeanUtils.copyProperties(SVCServiceRequestItemVO, Itempo);
                            Itempo.insertOrUpdate();
                            svcToSanyAppService.sendItemInfoToSanyApp(Itempo);
                            // 回传版本号
                            SVCServiceRequestItemVO.setRecordVersion(Itempo.getRecordVersion());

                            // 保存套餐子项

                            DbUnionCommonDto views = new DbUnionCommonDto();
                            views.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getnSvcFromBillID());
                            views.setQueryConditions("a.NSuitID", 0, bookItem.getnItemID());
                            List<SVCBookSuitItemVO> SVCBookSuitItemList =
                                    sVCBookSuitItemVOMapper.sVCBookSuitItemVO(views);

                            if (SVCBookSuitItemList != null && SVCBookSuitItemList.size() > 0) {
                                for (SVCBookSuitItemVO SVCBookSuitItemVO : SVCBookSuitItemList) {
                                    SvcOrderSuitItemPO SVCServiceRequestSuitItemVO = new SvcOrderSuitItemPO();
                                    SVCServiceRequestSuitItemVO.setnMainID(SVCServiceRequestVO.getiD());
                                    SVCServiceRequestSuitItemVO.setnItemID(SVCBookSuitItemVO.getnItemID());
                                    SVCServiceRequestSuitItemVO.setnSubItemID(SVCBookSuitItemVO.getnItemID());
                                    SVCServiceRequestSuitItemVO.setvSubItem(SVCBookSuitItemVO.getvItem());
                                    SVCServiceRequestSuitItemVO.setvSubItemName(SVCBookSuitItemVO.getvItemName());
                                    SVCServiceRequestSuitItemVO.setnManhaur(SVCBookSuitItemVO.getnManhaur());
                                    SVCServiceRequestSuitItemVO.setnManhaurFee(SVCBookSuitItemVO.getnManhaurFee());
                                    SVCServiceRequestSuitItemVO.setnDID(userInfo.getnDID());
                                    SVCServiceRequestSuitItemVO.insertOrUpdate();
                                }
                            }
                        }
                    }

                    List<SVCServiceRequestItemVODTO> itemList =
                            SelfGetItemByMainID(SVCServiceRequestVO.getiD());
                    if (itemList != null && itemList.size() > 0) {
                        // 设置第一行选中

                        map.put("SVCServiceRequestItemVO", itemList);
                    }

                    // 转入预约备件
                    DbUnionCommonDto CheckView = new DbUnionCommonDto();
                    CheckView.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getnSvcFromBillID());
                    // 执行SQL语句
                    List<SVCBookSPAVO> bookSpaList =
                            sVCBookSPAVOMapper.sVCBookSPAVO(
                                    userInfo.getnDID(), userInfo.getnCustGroupId(), CheckView);

                    if (bookSpaList != null && bookSpaList.size() > 0) {
                        for (SVCBookSPAVO bookSpa : bookSpaList) {
                            SVCServiceRequestSpaDTO SVCServiceRequestSpaVO = new SVCServiceRequestSpaDTO();
                            SVCServiceRequestSpaVO.setnMainID(SVCServiceRequestVO.getiD());
                            SVCServiceRequestSpaVO.setvModule(bookSpa.getvModule());
                            SVCServiceRequestSpaVO.setvSpa(bookSpa.getvSpa());
                            SVCServiceRequestSpaVO.setvSpaAlias(bookSpa.getvSpaName());
                            SVCServiceRequestSpaVO.setvKind(vDefaultKind);
                            SVCServiceRequestSpaVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());

                            // SVCServiceRequestSpaVO.SetProperty("NPrice", bookSpa.GetDecimal("NSalPrice"));
                            // modi by xh at 20170606 改成预约单本身的价格
                            SVCServiceRequestSpaVO.setnPrice(bookSpa.getfCkdj());
                            SVCServiceRequestSpaVO.setnQty(bookSpa.getnQty());
                            SVCServiceRequestSpaVO.setdOut(now);
                            SVCServiceRequestSpaVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestSpaVO.setvWH(bookSpa.getvWH());
                            SVCServiceRequestSpaVO.setvChannel(bookSpa.getvChannel());
//                            SVCServiceRequestSpaVO.setnPrice(bookSpa.getnSalPrice());

                            SvcOrderSpaPO spapo = new SvcOrderSpaPO();
                            BeanUtils.copyProperties(SVCServiceRequestSpaVO, spapo);
                            spapo.insertOrUpdate();
                        }

                        List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(SVCServiceRequestVO.getiD());
                        if (spaList != null && spaList.size() > 0) {
                            // 设置第一行选中

                            map.put("sVCServiceRequestSpaVO", spaList);
                        }
                    }
                }
            }


            // 来源估算
            else if ("1".equals(SVCServiceRequestVO.getvSvcFrom())) {
                // 更新估算单
                DbUnionCommonDto query = new DbUnionCommonDto();
                query.setQueryConditions("a.ID", 0, SVCServiceRequestVO.getnSvcFromBillID());
                List<SVCEstimateViewDTO> SVCEstimateList = svc0201SvcEstimateMapper.sVCEstimateVO(query);

                if (SVCEstimateList != null && SVCEstimateList.size() > 0) {
                    SvcEstimatePO stimtepo = new SvcEstimatePO();
                    // 委托书中插入
                    String NTaskID = SVCEstimateList.get(0).getnTaskID();
                    if (!StringUtils.isNullOrEmpty(NTaskID)) {
                        SvcOrderPO SVCPO = new SvcOrderPO();
                        QueryWrapper<SvcOrderPO> svcupdate = new QueryWrapper<>();
                        svcupdate.eq("id", SVCServiceRequestVO.getiD());
                        List<SvcOrderPO> svclist = SVCPO.selectList(svcupdate);
                        if (svclist != null && svclist.size() > 0) {
                            BeanUtils.copyProperties(svclist.get(0), SVCPO);
                            SVCPO.setnTaskID(NTaskID);
                            SVCPO.updateById();
                        }
                    }

                    QueryWrapper<SvcEstimatePO> updatePo = new QueryWrapper<>();
                    updatePo.eq("id", SVCEstimateList.get(0).getiD());
                    List<SvcEstimatePO> list = stimtepo.selectList(updatePo);
                    BeanUtils.copyProperties(list.get(0), stimtepo);
                    stimtepo.setvProcessSt("01");
                    stimtepo.setnEnterID(SVCServiceRequestVO.getiD());
                    stimtepo.updateById();

                    if(("1").equals(stimtepo.getvSvcFrom())){
                        //处理预约单
                        SvcBookRegisterPO svcBookRegisterPO = new SvcBookRegisterPO();
                        svcBookRegisterPO.setiD(stimtepo.getnSvcFromBillID());
                        svcBookRegisterPO = svcBookRegisterPO.selectById();
                        if(!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(svcBookRegisterPO.getiD())){
                            svcBookRegisterPO.setvExecuteStatus("02");
                            svcBookRegisterPO.setvBillStatus("3");
                            svcBookRegisterPO.setdSxrq(SVCServiceRequestVO.getdEnter());
                            svcBookRegisterPO.setvWtsbh(SVCServiceRequestVO.getvBillNO());
                            svcBookRegisterPO.setIsTransform(1);

                            BookOrderInfoToSanyAppTask bookOrderInfoToSanyAppTask = new BookOrderInfoToSanyAppTask(svcBookRegisterPO);
                            ExecutorManager.execute(bookOrderInfoToSanyAppTask);

                            svcBookRegisterPO.updateById();

                            SvcWeChatLogPO LogPO = new SvcWeChatLogPO();
                            LogPO.setId(UUID.randomUUID().toString());
                            LogPO.setVType("03");//非取消、失效状态	03
                            LogPO.setDCreate(now);
                            LogPO.setDImp(now);
                            LogPO.setVTrans("SVC0233");
                            LogPO.setVContent("预约进厂：客户已进厂，生成委托书" +
                                    po.getvBillNO()
                                    );
                            LogPO.setVEntity("tt_svc_book_register");
                            LogPO.setNdid(userInfo.getnDID());
                            LogPO.setNbid(userInfo.getnBID());
                            LogPO.setNOprID(userInfo.getiD());
                            LogPO.setVOpr(userInfo.getvPerson());
                            LogPO.setVOprName(userInfo.getvPersonName());
                            LogPO.setnMainID(svcBookRegisterPO.getiD());
                            LogPO.insertOrUpdate();
                        }

                    }


                    // 转入估算项目
                    // SVCEstimateItemsVO
                    DbUnionCommonDto viewxm = new DbUnionCommonDto();
                    viewxm.setQueryConditions("a.NMainID", 0, SVCEstimateList.get(0).getiD());
                    viewxm.setQueryConditions("a.ndid", 0, userInfo.getnDID());
                    List<SvcEstimateItemsDTO> estItemList = svcEstimateItemsMapper.view(viewxm);

                    if (estItemList != null && estItemList.size() > 0) {
                        for (SvcEstimateItemsDTO estItem : estItemList) {
                            SvcOrderItemPO SVCServiceRequestItemVO = new SvcOrderItemPO();

                            SVCServiceRequestItemVO.setnMainID(SVCServiceRequestVO.getiD());
                            SVCServiceRequestItemVO.setvItem(estItem.getvItem());
                            SVCServiceRequestItemVO.setvItemName(estItem.getvItemName());
                            if (SVCEstimateList.get(0).getvSvcKind() != null
                                    && SVCEstimateList.get(0).getvSvcKind().equals(SVCServiceRequestVO.getvSvcKind())
                                    && !StringUtils.isNullOrEmpty(estItem.getvKind())) {
                                SVCServiceRequestItemVO.setvKind(estItem.getvKind());
                            } else {
                                SVCServiceRequestItemVO.setvKind(vDefaultKind);
                            }
                            SVCServiceRequestItemVO.setnManhaur(estItem.getnManhaur());
                            SVCServiceRequestItemVO.setnManhaurFee(estItem.getnManhaurFee());
                            SVCServiceRequestItemVO.setvAdditionalDesc(estItem.getvAdditionalDesc());
                            SVCServiceRequestItemVO.setvItemProperty(estItem.getvItemProperty());
                            SVCServiceRequestItemVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                            SVCServiceRequestItemVO.setnItemID(estItem.getnItemID());
                            SVCServiceRequestItemVO.setcCommItem(estItem.getcCommItem());
                            SVCServiceRequestItemVO.setcDownload(estItem.getcDownload());
                            SVCServiceRequestItemVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestItemVO.setnSVCAdviserID(SVCServiceRequestVO.getnSVCAdviserID());
                            SVCServiceRequestItemVO.setvAudatexItem(estItem.getvAudatexItem());
                            SVCServiceRequestItemVO.setvMainPart(estItem.getvMainPart());
                            SVCServiceRequestItemVO.setvOperateStatus("00");
                            SVCServiceRequestItemVO.insertOrUpdate();
                            svcToSanyAppService.sendItemInfoToSanyApp(SVCServiceRequestItemVO);
                        }
                    }

                    // 转入估算备件
                    // SVCEstimateMaterialVO
                    DbUnionCommonDto viewstSpa = new DbUnionCommonDto();
                    viewstSpa.setQueryConditions("a.NMainID", 0, SVCEstimateList.get(0).getiD());
                    viewstSpa.setQueryConditions("a.ndid", 0, SVCEstimateList.get(0).getnDID());
                    List<SVCEstimateMaterialVO> estSpaList = svc0101Mapper.SVCEstimateMaterial(viewstSpa);

                    if (estSpaList != null && estSpaList.size() > 0) {
                        for (SVCEstimateMaterialVO estSpa : estSpaList) {
                            SvcOrderSpaPO SVCServiceRequestSpaVO = new SvcOrderSpaPO();
                            SVCServiceRequestSpaVO.setnMainID(SVCServiceRequestVO.getiD());
                            SVCServiceRequestSpaVO.setvModule(estSpa.getvModule());
                            SVCServiceRequestSpaVO.setvSpa(estSpa.getvSpa());
                            SVCServiceRequestSpaVO.setvSpaAlias(estSpa.getvSpaAlias());
                            if (SVCEstimateList.get(0).getvSvcKind() != null
                                    && SVCEstimateList.get(0).getvSvcKind().equals(SVCServiceRequestVO.getvSvcKind())
                                    && !StringUtils.isNullOrEmpty(estSpa.getvKind())) {
                                SVCServiceRequestSpaVO.setvKind(estSpa.getvKind());
                            } else {
                                SVCServiceRequestSpaVO.setvKind(vDefaultKind);
                            }
                            SVCServiceRequestSpaVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                            SVCServiceRequestSpaVO.setnPrice(estSpa.getnOutPrice());
                            SVCServiceRequestSpaVO.setnQty(estSpa.getnOutQty());
                            SVCServiceRequestSpaVO.setdOut(now);
                            SVCServiceRequestSpaVO.setnDID(SVCServiceRequestVO.getnDID());
                            SVCServiceRequestSpaVO.setvAudatexSpa(estSpa.getvAudatexSpa());
                            SVCServiceRequestSpaVO.setvWH(estSpa.getvWH());
                            SVCServiceRequestSpaVO.setvChannel(estSpa.getvChannel());
                            SVCServiceRequestSpaVO.insertOrUpdate();
                        }
                    }
                }
            }



            //无nMainId保存

            // 预估备件的保存需要 委托书 和备件列表2个
            SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO = new SaveSVCServiceRequestSpaVO();
            saveSVCServiceRequestSpaVO.setsVCServiceRequestSpaVO(sVCServiceRequestSpaVO);
            saveSVCServiceRequestSpaVO.setsVCServiceRequestVO(SVCServiceRequestVO);
//
            Map<String, Object> bSpaFlag = dosavespa(saveSVCServiceRequestSpaVO);
            if (!"1".equals(bSpaFlag.get("resType"))) {
                return map;
            }




            //更新全网档案
            //新建委托书 查询此车是否存在于拉取全网客户档案的车辆中，若存在，更新此底盘号开单数量+1 只统计当天的底盘开单数。
            svc0101_allarchivesService.updateOrderNum(SVCServiceRequestVO.getvVin());

            // 新建工单给透明车间传接口
//            OrderInfoToEwsTask task = new OrderInfoToEwsTask(userInfo.getnDID(), SVCServiceRequestVO.getiD(), "A");
//            ExecutorManager.execute(task);

//            this.svcToSanyAppService.sendToSanyApp(SVCServiceRequestVO.getiD(),userInfo.getnDID());

        } else {
            // 更新委托书
            SVCServiceRequestVO.setdOpr(LocalDateTime.now());
            if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCus())) {
                SVCServiceRequestVO.setvCus(CRMCustomer.getvCus());
            }
            if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getcDelete().toString())) {
                SVCServiceRequestVO.setcDelete(0);
            }
            if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getcPDIS().toString())) {
                SVCServiceRequestVO.setcPDIS(0);
            }
            SvcOrderPO po = new SvcOrderPO();
            BeanUtils.copyProperties(SVCServiceRequestVO, po);
            SVCServiceRequestVO.setRecordVersion(po.getRecordVersion());

            /****************20201201逄海添加 如果委托书修改了服务顾问，添加重要操作日志***********************************/
            //取得旧服务顾问
            SvcOrderPO svcOrderSearchPO = new SvcOrderPO();
            svcOrderSearchPO.setiD(getID);
            svcOrderSearchPO = svcOrderSearchPO.selectById();
            String oldSvcAdviserID = svcOrderSearchPO.getnSVCAdviserID();
            String oldOrderType = svcOrderSearchPO.getvOrderType();
            if (!oldSvcAdviserID.equals(SVCServiceRequestVO.getnSVCAdviserID())) {
                String vOldPerName = svcOrderSearchPO.getnSVCAdviserID();
                String vNewPerName = SVCServiceRequestVO.getnSVCAdviserID();
                UserPO userPO = new UserPO();
                userPO.setiD(svcOrderSearchPO.getnSVCAdviserID());
                userPO = userPO.selectById();
                if (userPO != null && !com.vw.mep.dms.function.StringUtils.isNullOrEmptyByUUid(userPO.getiD())) {
                    vOldPerName = userPO.getvPersonName();
                }
                UserPO userPONew = new UserPO();
                userPONew.setiD(SVCServiceRequestVO.getnSVCAdviserID());
                userPONew = userPONew.selectById();
                if (userPONew != null && !com.vw.mep.dms.function.StringUtils.isNullOrEmptyByUUid(userPONew.getiD())) {
                    vNewPerName = userPONew.getvPersonName();
                }
                // 记录重要操作日志
                SysTemOtherLogPO sysTemOtherLogPO = new SysTemOtherLogPO();
                sysTemOtherLogPO.setId(UUID.randomUUID().toString());
                sysTemOtherLogPO.setVType("ChgBill");
                sysTemOtherLogPO.setDCreate(LocalDateTime.now());
                sysTemOtherLogPO.setDImp(LocalDateTime.now());
                sysTemOtherLogPO.setVTrans("SVC0101");
                sysTemOtherLogPO.setVEntity("SvcOrderPO");
                sysTemOtherLogPO.setNOprID(userInfo.getiD());
                sysTemOtherLogPO.setVOpr(userInfo.getvPerson());
                sysTemOtherLogPO.setVOprName(userInfo.getvPersonName());
                sysTemOtherLogPO.setNbid(userInfo.getnBID());
                sysTemOtherLogPO.setNdid(userInfo.getnDID());
                String vContent =
                        "修改委托书【"
                                + SVCServiceRequestVO.getvBillNO()
                                + "】,服务顾问从【"
                                + vOldPerName
                                + "】改为 "
                                + vNewPerName
                                + " 】。";
                sysTemOtherLogPO.setVContent(vContent);
                sysTemOtherLogPO.insert();

            }
            /****************20201201逄海添加 如果委托书修改了服务顾问，添加重要操作日志***********************************/
            //如果在三包期内更新字段 vWarrantyState = 0
            if ("1".equals(SVCServiceRequestVO.getvSvcKind()) && "01".equals(SVCServiceRequestVO.getvClass()) && !"LFV000000WW000000".equals(SVCServiceRequestVO.getvVin())) {
                SVCServiceRequestVO checkSANBAO = new SVCServiceRequestVO();
                checkSANBAO.setnBID(userInfo.getnBID());
                checkSANBAO.setdBuy(SVCServiceRequestVO.getdBuy());
                checkSANBAO.setnMileage(SVCServiceRequestVO.getnMileage());
                Map<String, Object> sanbaoMap = checkGuarantee(checkSANBAO);
                String isInGuarantee = sanbaoMap.get("isInGuarantee") + "";
                if ("1".equals(isInGuarantee)) {
                    po.setvWarrantyState("0");
                }
            }

            /***************发送至客户小程序标识变更时，同步小程序库**********************/
            String sendFlagOld = com.vw.mep.dms.function.StringUtils.isNullOrEmpty(svcOrderSearchPO.getvAppCusResponse()) ? "0" : svcOrderSearchPO.getvAppCusResponse();
            String sendFlag = com.vw.mep.dms.function.StringUtils.isNullOrEmpty(po.getvAppCusResponse()) ? "0" : po.getvAppCusResponse();
            if(!sendFlagOld.equals(sendFlag)){
                svcToSanyAppService.sendToSanyApp(po);
            }
            /***************发送至客户小程序标识变更时，同步小程序库**********************/
            
            po.insertOrUpdate();
            SVCServiceRequestVO.setRecordVersion(po.getRecordVersion());

//            //订单类型变更，调用crm接口重新生成订单
//            if(!po.getvOrderType().equals(oldOrderType)){
//                //创建服务/销售订单
//                String useSanyCrm = stmCommonService.GetParameters("useSanyCrm", userInfo.getnDID(), "SVC");
//                if (("1").equals(useSanyCrm)) {
//                    String OBJECT_ID_SRV = SVCServiceRequestVO.getvObjectID();
//                    if (("01").equals(po.getvOrderType())) {
//                        // 根据ID 查询委托书
//                        DbUnionCommonDto view1 = new DbUnionCommonDto();
//                        view1.setQueryConditions("a.ID", 0, po.getiD());
//                        List<SVCServiceRequestVODTO> svclists = svc0104SvcOrderMapper.sVCServiceRequestVO(view1);
//                        if (svclists.size() > 0) {
//                            SvcServiceRequestViewDTO svcServiceRequestVO = new SvcServiceRequestViewDTO();
//                            BeanUtils.copyProperties(svclists.get(0), svcServiceRequestVO);
//                            SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO1 = new SaveSVCServiceRequestSpaVO();
//                            saveSVCServiceRequestSpaVO1.setsVCServiceRequestVO(svcServiceRequestVO);
//                            if (com.vw.mep.dms.function.StringUtils.isNullOrEmpty(OBJECT_ID_SRV)) {
//                                OBJECT_ID_SRV = svcToSanyCrmService.upLoadSpaToSanyCrm(saveSVCServiceRequestSpaVO1);
//                                po.setvObjectID(OBJECT_ID_SRV);
//                                po.insertOrUpdate();
//                            }
//                        }
//                    } else if ("02".equals(po.getvOrderType())) {
//                        //委托书信息
//                        SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
//                        svcSaleOrderInfoDTO.setZWTS_NO(userInfo.getvDealer() + "-" + po.getvBillNO());
//                        svcSaleOrderInfoDTO.setZDXC_NO(userInfo.getvDealer());
//                        svcSaleOrderInfoDTO.setCUST_NO(po.getvCus());
//                        svcSaleOrderInfoDTO.setZZEQUIPMENTNO(po.getvVin());
//                        svcSaleOrderInfoDTO.setiVOBJECTID(po.getvObjectID());
//
//                        List<SVCServiceRequestSpaDTO> svcServiceRequestSpaDTOS = sVC0101SaveVO.getsVCServiceRequestSpaVO();
//
//                        Map mapOrder = new HashMap();
//                        mapOrder.put("spas",svcServiceRequestSpaDTOS);
//                        mapOrder.put("svcSaleOrderInfoDTO",svcSaleOrderInfoDTO);
//
//                        this.svcToSanyCrmService.modifySaleOrder(mapOrder);
//
//                    }
//                }
//            }

            
            // 预估备件的保存需要 委托书 和备件列表2个
            SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO = new SaveSVCServiceRequestSpaVO();
            saveSVCServiceRequestSpaVO.setsVCServiceRequestSpaVO(sVCServiceRequestSpaVO);
            saveSVCServiceRequestSpaVO.setsVCServiceRequestVO(SVCServiceRequestVO);

            // 建议项目 保存需要 委托书和 项目列表
            DoSaveSugitIemVO doSaveSugitIemVO = new DoSaveSugitIemVO();
            // 是否显示历史维修项目
            doSaveSugitIemVO.setIsHasHistory(0);
            doSaveSugitIemVO.setsVCServiceRequestSugeestMitVO(sVCServiceRequestSugeestMitVO);
            doSaveSugitIemVO.setsVCServiceRequestVO(SVCServiceRequestVO);

            // 保存专用工具
            BatchSaveToolVO doSaveTool = new BatchSaveToolVO();
            doSaveTool.setsVCServiceRequestVO(SVCServiceRequestVO);
            doSaveTool.setsVCServiceRequestToolVO(sVCServiceRequestToolVO);

            Map<String, Object> bSpaFlag = dosavespa(saveSVCServiceRequestSpaVO);
            if (!"1".equals(bSpaFlag.get("resType"))) {
                return map;
            }
            Map<String, Object> bSugItemFlag = dosavesugitem(doSaveSugitIemVO);
            if (!"1".equals(bSugItemFlag.get("resType"))) {
                return map;
            }

            Map<String, Object> bTool = batchsavetool(doSaveTool);
            if (!"1".equals(bSugItemFlag.get("resType"))) {
                return map;
            }

            if ("01".equals(po.getvOrderType())){
                if(!StringUtils.isNullOrEmpty(po.getvObjectID())){
                    saveSVCServiceRequestSpaVO.setsVCServiceRequestVO(SVCServiceRequestVO);
                    saveSVCServiceRequestSpaVO.setsVCServiceRequestSpaVO(sVC0101SaveVO.getsVCServiceRequestSpaVO());
                    this.upLoadCRM(saveSVCServiceRequestSpaVO);
                }
//                SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO = new SaveSVCServiceRequestSpaVO();

            }

            else if ("02".equals(po.getvOrderType())) {
                //委托书信息
                String[] crmOrderNos = po.getvObjectID().split(";");
                SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
                svcSaleOrderInfoDTO.setiVOBJECTID(crmOrderNos[1]);

                List<SVCServiceRequestSpaDTO> svcServiceRequestSpaDTOS = sVC0101SaveVO.getsVCServiceRequestSpaVO();

                Map mapOrder = new HashMap();
                mapOrder.put("spas",svcServiceRequestSpaDTOS);
                mapOrder.put("svcSaleOrderInfoDTO",svcSaleOrderInfoDTO);

                this.svcToSanyCrmService.modifySaleOrder(mapOrder);

            }
        }

        // 保存客户和联系人

        CRMCustomer.setvLkName(SVCServiceRequestVO.getvLkName());
        CRMCustomer.setvLkMobile(SVCServiceRequestVO.getvLkMobile());
        CRMCustomer.setvLkTel(SVCServiceRequestVO.getvLkTel());
        if (StringUtils.isNullOrEmpty(CRMCustomer.getnMainid())) {
            CRMCustomer.setnMainid(svcid);
        }
        // 20200722修改 此处不做客户档案更新
        CRMCustomer.insertOrUpdate();

        // 保存本地库客户档案中的客户评价类别字段  暂时这个评价类别只有服务用，所以未同步到档案库
        if (!StringUtils.isNullOrEmpty(CRMCustomer.getvCus())) {
            CustomerPO customerPO = new CustomerPO();
            QueryWrapper<CustomerPO> cuspo = new QueryWrapper<>();
            cuspo.eq("vCus", CRMCustomer.getvCus());
            cuspo.eq("ndid", userInfo.getnDID());
            List<CustomerPO> Cuslist = customerPO.selectList(cuspo);
            if (Cuslist != null && Cuslist.size() > 0) {
                customerPO = Cuslist.get(0);
                customerPO.setvCusName(CRMCustomer.getvCusName());
                customerPO.setvMobile(CRMCustomer.getvCusMobile());
                //省市区县保存
                List<STMCityVODTO> ownerPlace = SVCServiceRequestVO.getvCityLink();
                customerPO = svcToCrmService.checkOwnerPlace(customerPO, SVCServiceRequestVO.getvAddrSre());
                customerPO.setvCusEvaClass(CRMCustomer.getvCusEvaClass());
                //更新客户详细地址
                customerPO.setvCusAddr(vCusAdress);
                customerPO.setvCusAddrDetail(vCusAdressDetail);
                customerPO.setnCityID(SVCServiceRequestVO.getnCityID());

                customerPO.updateById();

                //同步客户档案给档案服务
                CustomerInfoVO customerin = new CustomerInfoVO();
                BeanUtils.copyProperties(customerPO, customerin);
                customerin.setnCityId(customerPO.getnCityID());
                customerin.setBusiType("SVC0101");
                archivesFeignClient.saveCustomer(userInfo.getnDID(), userInfo.getiD(), userInfo.getiD(), customerin);


                //同步联系人档案给档案服务
                LinkmanPO linkmanPO = new LinkmanPO();
                QueryWrapper<LinkmanPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("nMainID", customerPO.getiD());
                queryWrapper.orderByDesc("updateOn");
                List<LinkmanPO> lkList = linkmanPO.selectList(queryWrapper);
                if (lkList != null && lkList.size() > 0) {
                    linkmanPO = lkList.get(0);
                    linkmanPO.setvLkName(CRMCustomer.getvLkName());
                    linkmanPO.setvLkMobile(CRMCustomer.getvLkMobile());
                    RelateInfoVO relateInfoVO = new RelateInfoVO();
                    BeanUtils.copyProperties(linkmanPO, relateInfoVO);
                    relateInfoVO.setvCardNo(customerPO.getvCus());
                    archivesFeignClient.saveRelate(userInfo.getnDID(), relateInfoVO);
                }


                //评价类别同步更新给档案库
                CustomerInfoVO customerInfoVO = new CustomerInfoVO();
                customerInfoVO.setiD(customerPO.getiD());
                customerInfoVO.setvCusEvaClass(customerPO.getvCusEvaClass());
                archivesFeignClient.updatevCusEvaClass(userInfo.getnDID(), customerInfoVO);
            }

        }

        // 保存车辆档案
        DbUnionCommonDto query = new DbUnionCommonDto();
        query.setQueryConditions("a.NDID", 0, SVCServiceRequestVO.getnDID());
        query.setQueryConditions("a.VVin", 0, SVCServiceRequestVO.getvVin());
        List<CRMVehicleQueryVoDTO> vehList = cRMVehicleQueryVOMapper.cRMVehicleQueryVO(query);
        if (vehList != null && vehList.size() > 0) {
            vehList.get(0).setvLicenseTag(SVCServiceRequestVO.getvLicenseTag());
            vehList.get(0).setnSaleTypeID(SVCServiceRequestVO.getnSaleTypeID());
            vehList.get(0).setnCusGrade(SVCServiceRequestVO.getnCusGrade());
            vehList.get(0).setnColorId(SVCServiceRequestVO.getnColorId());
            vehList.get(0).setdBuy(SVCServiceRequestVO.getdBuy());
            vehList.get(0).setdLicense(SVCServiceRequestVO.getdLicense());
            vehList.get(0).setvCus(SVCServiceRequestVO.getvCus());
            vehList.get(0).setcSVCSecondhand(SVCServiceRequestVO.getcSVCSecondhand() + "");
            vehList.get(0).setvCusName(SVCServiceRequestVO.getvCusName());
            vehList.get(0).setvMobile(SVCServiceRequestVO.getvCusMobile());
            vehList.get(0).setvTel(SVCServiceRequestVO.getvCusTel());
            vehList.get(0).setvLkTel(SVCServiceRequestVO.getvLkTel());
            vehList.get(0).setvLkName(SVCServiceRequestVO.getvLkName());
            vehList.get(0).setvLkMobile(SVCServiceRequestVO.getvLkMobile());
            // vehList.get(0).setnLKID("NLKID", lkRetModel.GetSDO("CRMLinkman").GetGuid());
            // 联系电话。姓名 移动电话 冗余到客户档
            vehList.get(0).setnMileage(SVCServiceRequestVO.getnMileage());
            vehList.get(0).setvRemark(SVCServiceRequestVO.getvVehRemark());
            vehList.get(0).setvCarType(SVCServiceRequestVO.getvCarType());
            vehList.get(0).setdProd(SVCServiceRequestVO.getdProd());
            vehList.get(0).setvEngineNo(SVCServiceRequestVO.getvEngineNo());
            vehList.get(0).setVolvo(SVCServiceRequestVO.getVolvo());
            vehList.get(0).setVolume(SVCServiceRequestVO.getVolume());
            vehList.get(0).setDeviceDesc(SVCServiceRequestVO.getDeviceDesc());
            vehList.get(0).setRunTimes(SVCServiceRequestVO.getRunTimes());

            // modified by xh at 20160526
            if ("00".equals(SVCServiceRequestVO.getvRepairStatus())) {

                // 计算JD和IA标识
                // IPUCCommonService pubService = (IPUCCommonService)this.GetService("PUCCommonService");
                JDIAResult serviceResult =
                        pUCCommonService.getJDIA(SVCServiceRequestVO.getdLicense(), now, userInfo.getnBID());
                int cJD = serviceResult.getcJD();
                int cIA = serviceResult.getcIA();

                vehList.get(0).setcJDP(cJD + "");
                vehList.get(0).setcIABS(cIA + "");
            }
            if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnSVCExcAdviserID())) {
                vehList.get(0).setnSVCExcAdviserID(SVCServiceRequestVO.getnSVCExcAdviserID());
            }
            // end modify by xh
            // EntityDefFactory.Update(vehList[0]);
            VehiclePO po = new VehiclePO();
            BeanUtils.copyProperties(vehList.get(0), po);
            int svcsecondhand = 0;
            if ("1".equals(vehList.get(0).getcSVCSecondhand())) {
                svcsecondhand = 1;
            }
            po.setcSVCSecondhand(svcsecondhand);
//            po.setnSVCExcAdviserID(vehList.get(0).getnSVCExcAdviserID());
            if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnSVCExcAdviserID())) {
                po.setnSVCExcAdviserID(SVCServiceRequestVO.getnSVCExcAdviserID());
            }
            po.setcJDP(Integer.parseInt(vehList.get(0).getcJDP()));
            po.setcIABS(Integer.parseInt(vehList.get(0).getcIABS()));
            po.setcOwnSell(Integer.parseInt(vehList.get(0).getcOwnSell() == null ? "0" : vehList.get(0).getcOwnSell()));
            // 保存车辆档案时候更新联系人信息
            po.setvLkName(SVCServiceRequestVO.getvLkName());
            po.setvLkMobile(SVCServiceRequestVO.getvLkMobile());
            po.setvLkTel(SVCServiceRequestVO.getvLkTel());
            po.insertOrUpdate();

        } else {
            VehiclePO CRMGetVehicleNewVO = new VehiclePO();
            CRMGetVehicleNewVO.setnDID(userInfo.getnDID());
            CRMGetVehicleNewVO.setvVin(SVCServiceRequestVO.getvVin());
            CRMGetVehicleNewVO.setdCreate(now);
            CRMGetVehicleNewVO.setvLicenseTag(SVCServiceRequestVO.getvLicenseTag());
            CRMGetVehicleNewVO.setnSaleTypeID(SVCServiceRequestVO.getnSaleTypeID());
            CRMGetVehicleNewVO.setnCusGrade(SVCServiceRequestVO.getnCusGrade());
            CRMGetVehicleNewVO.setnColorId(SVCServiceRequestVO.getnColorId());
            CRMGetVehicleNewVO.setdBuy(SVCServiceRequestVO.getdBuy());
            CRMGetVehicleNewVO.setdLicense(SVCServiceRequestVO.getdLicense());
            CRMGetVehicleNewVO.setnSVCExcAdviserID(SVCServiceRequestVO.getnSVCExcAdviserID());
            CRMGetVehicleNewVO.setcSVCSecondhand(SVCServiceRequestVO.getcSVCSecondhand());
            // 联系人 电话 姓名 移动电话

            CRMGetVehicleNewVO.setvLkName(SVCServiceRequestVO.getvLkName());
            CRMGetVehicleNewVO.setvLkMobile(SVCServiceRequestVO.getvLkMobile());
            CRMGetVehicleNewVO.setvLkTel(SVCServiceRequestVO.getvLkTel());
            CRMGetVehicleNewVO.setvCus(SVCServiceRequestVO.getvCus());
            CRMGetVehicleNewVO.setvMobile(SVCServiceRequestVO.getvCusMobile());
            CRMGetVehicleNewVO.setvTel(SVCServiceRequestVO.getvCusTel());
            // CRMGetVehicleNewVO.setnLkID(lkRetModel.GetSDO("CRMLinkman").GetGuid("ID"));
            CRMGetVehicleNewVO.setnMileage(SVCServiceRequestVO.getnMileage());
            CRMGetVehicleNewVO.setvRemark(SVCServiceRequestVO.getvVehRemark());
            CRMGetVehicleNewVO.setvCarType(SVCServiceRequestVO.getvCarType());
            CRMGetVehicleNewVO.setdProd(SVCServiceRequestVO.getdProd());
            CRMGetVehicleNewVO.setvEngineNo(SVCServiceRequestVO.getvEngineNo());
            CRMGetVehicleNewVO.setVolvo(SVCServiceRequestVO.getVolvo());
            CRMGetVehicleNewVO.setVolume(SVCServiceRequestVO.getVolume());
            CRMGetVehicleNewVO.setDeviceDesc(SVCServiceRequestVO.getDeviceDesc());
            CRMGetVehicleNewVO.setRunTimes(SVCServiceRequestVO.getRunTimes());
            if ("00".equals(SVCServiceRequestVO.getvRepairStatus())) {
                // 计算JD和IA标识
                // IPUCCommonService pubService = (IPUCCommonService)this.GetService("PUCCommonService");
                JDIAResult serviceResult =
                        pUCCommonService.getJDIA(SVCServiceRequestVO.getdLicense(), now, userInfo.getnBID());
                int cJD = serviceResult.getcJD();
                int cIA = serviceResult.getcIA();

                CRMGetVehicleNewVO.setcJDP(cJD);
                CRMGetVehicleNewVO.setcIABS(cIA);
            }
            LocalDateTime dstop = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
            CRMGetVehicleNewVO.setcStop(0);
            CRMGetVehicleNewVO.setdStop(dstop);
            // modified by xh at 20160526

            CRMGetVehicleNewVO.insertOrUpdate();
            if (!StringUtils.isNullOrEmpty(CRMGetVehicleNewVO.getvLicenseTag())) {
                //更新服务助手引导员业务表, 边缘业务, 新车辆时才回写,用户和车辆信息
                try {

                    GuideRecordDto guideRecord = new GuideRecordDto();
                    guideRecord.setLicenseTag(CRMGetVehicleNewVO.getvLicenseTag());
                    guideRecord.setCusName(CRMCustomer.getvCusName());
                    guideRecord.setAdviser(SVCServiceRequestVO.getAdviserPersonName());
                    guideRecord.setAdviserId(SVCServiceRequestVO.getAdviserPerson());
                    //接口内部 用新线程, 捕捉了异常, 不影响接车制单主流程.
                    svcAppService.updateGuideRecord(guideRecord);
                } catch (Exception e) {
                    //错了就错了
                }
            }
        }

        try {
            //保存完车档后同步车档数据到mq
            DbUnionCommonDto query1 = new DbUnionCommonDto();
            query1.setQueryConditions("a.NDID", 0, SVCServiceRequestVO.getnDID());
            query1.setQueryConditions("a.VVin", 0, SVCServiceRequestVO.getvVin());
            List<CRMVehicleQueryVoDTO> vehList1 = cRMVehicleQueryVOMapper.cRMVehicleQueryVO(query1);
            if (vehList1.size() > 0) {
                rabbitMqController.postMessage("tm_vehicle", vehList1.get(0).getiD());
            }
        } catch (Exception e) {
            logger.error("Exception", e);

        }


        // 如果级联更新在修委托书
        if ("1".equals(IsChageRepairing)) {
            SvcOrderPO SVCpo = new SvcOrderPO();
            QueryWrapper<SvcOrderPO> querySVC = new QueryWrapper<>();
            querySVC.eq("ndid", SVCServiceRequestVO.getnDID());
            querySVC.eq("vvin", SVCServiceRequestVO.getvVin());
            querySVC.eq("VRepairStatus", "00");
            querySVC.eq("CDelete", "0");
            querySVC.ne("VBillNO", SVCServiceRequestVO.getvBillNO());

            List<SvcOrderPO> SVCServiceRequestQAList = SVCpo.selectList(querySVC);
            if (SVCServiceRequestQAList != null && SVCServiceRequestQAList.size() > 0) {
                for (SvcOrderPO item : SVCServiceRequestQAList) {
                    SvcOrderCusinfoPO cusinPO = new SvcOrderCusinfoPO();
                    QueryWrapper<SvcOrderCusinfoPO> querycusin = new QueryWrapper<>();
                    querycusin.eq("nMainID", item.getiD());
                    List<SvcOrderCusinfoPO> cusinList = cusinPO.selectList(querycusin);
                    if (cusinList != null && cusinList.size() > 0) {
                        BeanUtils.copyProperties(cusinList.get(0), cusinPO);
                        cusinPO.setvCus(SVCServiceRequestVO.getvCus());
                        cusinPO.setvCusName(SVCServiceRequestVO.getvCusName());
                        cusinPO.setvCusTel(SVCServiceRequestVO.getvCusTel());
                        cusinPO.setvCusMobile(SVCServiceRequestVO.getvCusMobile());
                        cusinPO.setvCusAddr(SVCServiceRequestVO.getvCusAddr());
                        cusinPO.setvLkName(SVCServiceRequestVO.getvLkName());
                        cusinPO.setvLkTel(SVCServiceRequestVO.getvLkTel());
                        cusinPO.setvLkMobile(SVCServiceRequestVO.getvLkMobile());
                        cusinPO.setvLkAddr(SVCServiceRequestVO.getvLkAddr());
                        cusinPO.setvClass(SVCServiceRequestVO.getvClass());
                        cusinPO.updateById();
                    }
                }
            }
        }


//        // 查询回刷数据
//
//        String dBegin = SVCServiceRequestVO.getdEnter() + "";
//        String dEnd = SVCServiceRequestVO.getdEnter().plusDays(1) + "";
//        int cRepairing = 1;
//        String vDateType = "01";
//        int cConsultant = 0;
//        String keyWord = SVCServiceRequestVO.getvBillNO();
//        //将数据回填
//        SVCServiceRequestQueryParaVO svcServiceRequestQueryParaVO = new SVCServiceRequestQueryParaVO();
//        SVCServiceRequestQueryParaCM sVCServiceRequestQueryParaCM = new SVCServiceRequestQueryParaCM();
//        List<String> dEnters = new ArrayList<>();
//        dEnters.add(dBegin);
//        dEnters.add(dEnd);
//        sVCServiceRequestQueryParaCM.setdEnter(dEnters);
//        sVCServiceRequestQueryParaCM.setcRepairing(cRepairing);
//        sVCServiceRequestQueryParaCM.setvDateType(vDateType);
//        sVCServiceRequestQueryParaCM.setcConsultant(cConsultant);
//        sVCServiceRequestQueryParaCM.setKeyWord(keyWord);
//        svcServiceRequestQueryParaVO.setsVCServiceRequestQueryParaCM(sVCServiceRequestQueryParaCM);
//        Page<SVCGetServiceRequest> queryList1 =
//                dosearch(svcServiceRequestQueryParaVO).getTableData();
//
//        List<SVCGetServiceRequest> queryList = queryList1.getRecords();
//
//        if (queryList != null && queryList.size() > 0) {
//            map.put("sVCServiceRequestQueryListCM", queryList.get(0));
//        }
//
//        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
//        map.remove("isSaveSVC");
//        map.put("isSaveSVC", "1");

        // 查询回刷数据

        String dBegin = SVCServiceRequestVO.getdEnter() + "";
        String dEnd = SVCServiceRequestVO.getdEnter().plusDays(1) + "";
        int cRepairing = 1;
        String vDateType = "01";
        int cConsultant = 0;
        String keyWord = SVCServiceRequestVO.getvBillNO();

        Page<SVCGetServiceRequest> queryList1 =
                dosearch1(dBegin, dEnd, cRepairing, vDateType, cConsultant, keyWord, 1, 20);

        List<SVCGetServiceRequest> queryList = queryList1.getRecords();

        if (queryList != null && queryList.size() > 0) {
            map.put("sVCServiceRequestQueryListCM", queryList.get(0));
        }

        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        map.remove("isSaveSVC");
        map.put("isSaveSVC", "1");


        // 替换车 的 不要了
        // map.put("sVCQxControlCM",sVC0101SaveVO.getsVCQxControlCM());

        // 获取项目性质列表
        List<SVCItemKindSHVO> ItemKindlist =
                GetItemKindList(
                        SVCServiceRequestVO.getvSvcKind(),
                        "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                        SVCServiceRequestVO.getcFreeMaintain() + "",
                        SVCServiceRequestVO.getcExtraMaintain() + "");

        map.put("sVCItemKindSHVO", ItemKindlist);

        if ("1".equals(IsShowSeccessMsg)) {
            message.putMessage("SREMessage", "009");
            map.put("infor", message);
        }

        // 接口上传给润林数据
        sVC0101SaveVO.setsVCServiceRequestVO(SVCServiceRequestVO);
        savefreemt(sVC0101SaveVO);

        // 同步给sales的车辆客户关系
        SalCusCarPO salecuscar = new SalCusCarPO();
        salecuscar.setnDID(userInfo.getnDID());
        salecuscar.setvVin(SVCServiceRequestVO.getvVin());
        salecuscar.setvCus(SVCServiceRequestVO.getvCus());
        salecuscar.setCreateBy(SVCServiceRequestVO.getCreateBy());
        salecuscar.setCreateOn(SVCServiceRequestVO.getCreateOn());
        salecuscar.setUpdateBy(SVCServiceRequestVO.getUpdateBy());
        salecuscar.setUpdateOn(SVCServiceRequestVO.getUpdateOn());
        // TODO
        //        ssalFeignClient.syncCusCarInfo(userInfo.getnDID(),salecuscar);

        /**
         * 当委托书以救援进场的时候更新委托书编号到救援任务单中
         */

        SvcServiceRequestViewDTO svcServiceRequestViewDTO = sVC0101SaveVO.getsVCServiceRequestVO();
        if (svcServiceRequestViewDTO != null) {
            String vSvcFrom = svcServiceRequestViewDTO.getvSvcFrom();
            if (!StringUtils.isNullOrEmpty(vSvcFrom)) {
                if ("2".equals(vSvcFrom)) {
                    String nSvcFromBillID = sVC0101SaveVO.getsVCServiceRequestVO().getnSvcFromBillID();
                    Svc0204RescueBillVO rescueBillVO = new Svc0204RescueBillVO();
                    Svc0204RescueBillDTO svc0204RescueBillDTO = new Svc0204RescueBillDTO();
                    svc0204RescueBillDTO.setvBillNO(nSvcFromBillID);
                    svc0204RescueBillDTO.setvSvcBillNO(SVCServiceRequestVO.getvBillNO());
                    rescueBillVO.setMain(svc0204RescueBillDTO);
                    svc0204Service.updateBill(rescueBillVO);
                }
            }
        }
        // 新建工单给透明车间传接口
        OrderInfoToEwsTask task = new OrderInfoToEwsTask(userInfo.getnDID(), SVCServiceRequestVO.getiD(), "U");
        ExecutorManager.execute(task);


        /*************20210107  panghai 委托书保存时，可以修改工时工时费*********************************************/
        List<SVCServiceRequestItemVODTO> itemList = sVC0101SaveVO.getsVCServiceRequestItemVO();
        if (itemList != null && !itemList.isEmpty()) {
            for (SVCServiceRequestItemVODTO item : itemList
            ) {
                String itemId = item.getiD();
                if (!StringUtils.isNullOrEmpty(itemId)) {
                    SvcOrderItemPO svcOrderItemPO = new SvcOrderItemPO();
                    svcOrderItemPO.setiD(itemId);
                    svcOrderItemPO = svcOrderItemPO.selectById();
                    if (!StringUtils.isNullOrEmpty(svcOrderItemPO.getiD())) {
                        svcOrderItemPO.setnManhaur(item.getnManhaur());
                        svcOrderItemPO.setnManhaurFee(item.getnManhaurFee());
                        svcOrderItemPO.updateById();
                    }
                }
            }
        }
        /*************20210107  panghai 委托书保存时，可以修改工时工时费*********************************************/


        return map;
    }

    // 保存委托书信息
    @Transactional
    @Override
    public Map<String, Object> savesvcservicerequestvo(SvcServiceRequestViewDTO SVCServiceRequestVO)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
    /*     svcServiceRequestViewDTO.setiD(svcid);
    SvcOrderPO po = new SvcOrderPO();

    BeanUtils.copyProperties(svcServiceRequestViewDTO, po);
    po.insertOrUpdate();
    // 更新启明客户信息
    SvcOrderCusinfoPO Cuspo = new SvcOrderCusinfoPO();
    QueryWrapper<SvcOrderCusinfoPO> query  = new QueryWrapper<>();
    query.eq("nMainid",svcServiceRequestViewDTO.getiD());
    List<SvcOrderCusinfoPO> listPO = Cuspo.selectList(query);
    //查找到了 更新
    if((!listPO.isEmpty())&&listPO.size() > 0)
    {
        //客户代码
        listPO.get(0).setvCus(svcServiceRequestViewDTO.getvCus());
        //客户名称
        listPO.get(0).setvCusName(svcServiceRequestViewDTO.getvCusName());
        //客户移动电话
        listPO.get(0).setvCusMobile(svcServiceRequestViewDTO.getvCusMobile());
        //客户电话
        listPO.get(0).setvCusTel(svcServiceRequestViewDTO.getvCusTel());
        //客户类别
        listPO.get(0).setvClass(svcServiceRequestViewDTO.getvClass());
        //联系人姓名
        listPO.get(0).setvLkName(svcServiceRequestViewDTO.getvLkName());
        //联系人移动电话
        listPO.get(0).setvLkMobile(svcServiceRequestViewDTO.getvLkMobile());
        //联系人电话
        listPO.get(0).setvLkTel(svcServiceRequestViewDTO.getvLkTel());
        //评价类别
        listPO.get(0).setvCusEvaClass(svcServiceRequestViewDTO.getvCusEvaClass());
        //方便联系时间
        listPO.get(0).setvConstractTime(svcServiceRequestViewDTO.getvConstractTime());
        //希望联系方式
        listPO.get(0).setvConstractType(svcServiceRequestViewDTO.getvConstractType());
        //客户地址
        listPO.get(0).setvCusAddr(svcServiceRequestViewDTO.getvCusAddr());
        BeanUtils.copyProperties(listPO.get(0), Cuspo);

        Cuspo.updateById();
    }else
    {
        //插入新的客户信息
        //客户代码
        Cuspo.setvCus(svcServiceRequestViewDTO.getvCus());
        //客户名称
        Cuspo.setvCusName(svcServiceRequestViewDTO.getvCusName());
        //客户移动电话
        Cuspo.setvCusMobile(svcServiceRequestViewDTO.getvCusMobile());
        //客户电话
        Cuspo.setvCusTel(svcServiceRequestViewDTO.getvCusTel());
        //客户类别
        Cuspo.setvClass(svcServiceRequestViewDTO.getvClass());
        //联系人姓名
        Cuspo.setvLkName(svcServiceRequestViewDTO.getvLkName());
        //联系人移动电话
        Cuspo.setvLkMobile(svcServiceRequestViewDTO.getvLkMobile());
        //联系人电话
        Cuspo.setvLkTel(svcServiceRequestViewDTO.getvLkTel());
        //评价类别
        Cuspo.setvCusEvaClass(svcServiceRequestViewDTO.getvCusEvaClass());
        //方便联系时间
        Cuspo.setvConstractTime(svcServiceRequestViewDTO.getvConstractTime());
        //希望联系方式
        Cuspo.setvConstractType(svcServiceRequestViewDTO.getvConstractType());
        //客户地址
        Cuspo.setvCusAddr(svcServiceRequestViewDTO.getvCusAddr());

        Cuspo.insert();
    }
    // 上传润林客户档案，联系人档案

    map.put("sVCServiceRequestVO",svcServiceRequestViewDTO);*/
        return map;
    }

    // 保存委托书中预估备件
    //1、在数据库中保存
    //2、同步crm
    @Transactional
    @Override
    public Map<String, Object> dosavespa(SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        String resType = "1";
        SvcServiceRequestViewDTO SVCServiceRequestVO =
                saveSVCServiceRequestSpaVO.getsVCServiceRequestVO();
        // 预估备件
        List<SVCServiceRequestSpaDTO> list = saveSVCServiceRequestSpaVO.getsVCServiceRequestSpaVO();
        if (list != null && !list.isEmpty()) {
            // Update 预估备件模型
            List<SVCServiceRequestSpaDTO> HasUpdate = new ArrayList<>();
            // Insert 预估备件模型
            List<SVCServiceRequestSpaDTO> HasInsert = new ArrayList<>();

            for (int i = 0; i < list.size(); i++) {
                // 判断是新增还是更新
                String sapID = list.get(i).getiD();
                if (!StringUtils.isNullOrEmpty(sapID)) {
                    HasUpdate.add(list.get(i));
                } else {
                    HasInsert.add(list.get(i));
                }
            }
            // 更新
            if ((HasUpdate != null) && HasUpdate.size() > 0) {
                for (SVCServiceRequestSpaDTO item : HasUpdate) {
                    if (StringUtils.isNullOrEmpty(item.getvSpa())) {
                        message.putMessage("SVCMessage", "125", new String[]{"预估备件代码不可为空"});
                        map.put("err", message);
                        return map;
                    }
                    // 校验通过，执行更新
                    SvcOrderSpaPO po = new SvcOrderSpaPO();
                    po.setiD(item.getiD());
                    Integer recordVersion = po.selectById().getRecordVersion();
                    BeanUtils.copyProperties(item, po);
                    po.setvSpaAlias(item.getvSpaAlias());
                    po.setRecordVersion(recordVersion);
                    po.updateById();
                }
            }
            // 新建
            if ((HasInsert != null) && HasInsert.size() > 0) {
                for (int i = 0; i < HasInsert.size(); i++) {
                    if (StringUtils.isNullOrEmpty(HasInsert.get(i).getvSpa())) {
                        message.putMessage("SVCMessage", "125", new String[]{"预估备件代码不可为空"});
                        map.put("err", message);
                        return map;
                    }
                    // 校验备件是否已经存在
                    DbUnionCommonDto preSPAView = new DbUnionCommonDto();
                    DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
                    preSPAView.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
                    preSPAView.setQueryConditions("a.ndid", 0, userInfor.getnDID());
                    preSPAView.setQueryConditions("a.VSpa", 0, HasInsert.get(i).getvSpa());
                    List<SVCServiceRequestSpaDTO> checkList =
                            svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(preSPAView);
                    if (checkList != null && checkList.size() > 0) {
                        message.putMessage(
                                "SVCMessage",
                                "006",
                                new String[]{"备件", HasInsert.get(i).getvSpa()}); // {0}{1}已经存在!"
                        return map;
                    } else {
                        HasInsert.get(i).setnMainID(SVCServiceRequestVO.getiD());
                        HasInsert.get(i).setnDID(SVCServiceRequestVO.getnDID());
                        HasInsert.get(i).setvWorkProp(SVCServiceRequestVO.getvSvcKind());
                        SvcOrderSpaPO po = new SvcOrderSpaPO();
                        BeanUtils.copyProperties(HasInsert.get(i), po);
                        po.setvSpaAlias(HasInsert.get(i).getvSpaAlias());
                        po.insert();
                    }
                }
            }

            if (("01").equals(SVCServiceRequestVO.getvOrderType())){
                //vObjectID 是在外面第一次调
                //OBJECT_ID_SRV = svcToSanyCrmService.upLoadSpaToSanyCrm(saveSVCServiceRequestSpaVO1) 时保存的
                //这里是第二次调 svcToSanyCrmService.upLoadSpaToSanyCrm，真正保存备件到crm
                if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvObjectID())){
                    this.upLoadCRM(saveSVCServiceRequestSpaVO);
                }
            }else if (("02").equals(SVCServiceRequestVO.getvOrderType())){
                List<SVCServiceRequestSpaDTO> spaDTOS = new ArrayList<>();
                HasUpdate.forEach(t->{
                    t.setCrmSpaStatus("U");
                });
                HasInsert.forEach(t->{
                    t.setCrmSpaStatus("I");
                });
                HasUpdate.addAll(HasInsert);
                this.modifySaleOrder(SVCServiceRequestVO.getvObjectID().split(";")[1],HasUpdate);
            }
        }

        // 获取预估备件
        List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(SVCServiceRequestVO.getiD());
        map.put("sVCServiceRequestSpaVO", spaList);
        map.put("resType", resType);



        return map;
    }

    // 删除预估备件
    @Override
    public Map<String, Object> dodeletespa(SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO) {
        Map<String, Object> map = new HashMap<>();
        List<String> servicePackList = new ArrayList<>();

        SvcServiceRequestViewDTO SVCServiceRequestVO =
                saveSVCServiceRequestSpaVO.getsVCServiceRequestVO();
        List<SVCServiceRequestSpaDTO> itemList = saveSVCServiceRequestSpaVO.getsVCServiceRequestSpaVO();
        if (itemList != null && itemList.size() > 0) {
            // 校验委托书状态
            Map<String, Object> svcModel = CheckSvcBillState(SVCServiceRequestVO.getiD());
            // 抛错误消息
            String err = svcModel.get("err") + "";
            if (StringUtils.isNullOrEmpty(err)) {
                message.putMessage("err", err);
                map.put("err", message);
                return map;
            }

            // 回退优惠包次数
            // 会员的
            for (SVCServiceRequestSpaDTO item : itemList) {
                String id = item.getiD();
                if (!StringUtils.isNullOrEmpty(id)) {
                    SvcOrderSpaPO po = new SvcOrderSpaPO();
                    po.deleteById(id);
                }
//
            }
            if (("01").equals(SVCServiceRequestVO.getvOrderType())){
                List<SVCServiceRequestSpaDTO> itemListUpload = new ArrayList<>();
                for (int i = 0; i < itemList.size(); i++) {
                    //判断之前是否已经上传过，如果没有上传，不调用CRM接口，直接删除
                    if (("1").equals(itemList.get(i).getcUpload())){
                        itemListUpload.add(itemList.get(i));
                    }
                }

                String vSpas = "";
                for (SVCServiceRequestSpaDTO item: itemListUpload) {
                    String vSpa = item.getvSpa();
                    SpaGetDrawDetailForSvcVODTO spaGetDrawDetailForSvcVODTO = this.svc0104SvcOrderMapper.getDrawDetailForOrderByVSpa(item.getnDID(),item.getnMainID(),vSpa);
                    if (spaGetDrawDetailForSvcVODTO != null && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(spaGetDrawDetailForSvcVODTO.getvSpa())){
                        if (null != spaGetDrawDetailForSvcVODTO.getnQty() && BigDecimal.ZERO.compareTo(spaGetDrawDetailForSvcVODTO.getnQty()) != 0){
                            vSpas = vSpas + "【" + vSpa + "】" + "、";
                        }
                    }
                }
                if (!StringUtils.isNullOrEmpty(vSpas)){
                    vSpas = vSpas.substring(0, vSpas.length() -1);
                    message.putMessage("SVCMessage", "125", new String[]{vSpas + "配件未完全退库，请在CRM退库后进行操作"});
                }else{
                    this.svcToSanyCrmService.deleteSpaToSanyCrm(itemListUpload,SVCServiceRequestVO.getvBillNO());
                    //成功之后删除配件
                    for (SVCServiceRequestSpaDTO item:
                            itemListUpload) {
                        SvcUploadCrmSpaPO svcUploadCrmSpaPO = new SvcUploadCrmSpaPO();
                        QueryWrapper<SvcUploadCrmSpaPO> svcUploadCrmSpaPOQueryWrapper = new QueryWrapper<>();
                        svcUploadCrmSpaPOQueryWrapper.eq("vspa",item.getvSpa());
                        svcUploadCrmSpaPOQueryWrapper.eq("ndid",item.getnDID());
                        svcUploadCrmSpaPOQueryWrapper.eq("nmainid",item.getnMainID());
                        svcUploadCrmSpaPO = svcUploadCrmSpaPO.selectOne(svcUploadCrmSpaPOQueryWrapper);
                        if (svcUploadCrmSpaPO != null && !StringUtils.isNullOrEmpty(svcUploadCrmSpaPO.getiD())){
                            if (svcUploadCrmSpaPO.getnQty().compareTo(BigDecimal.ZERO) != 0 || svcUploadCrmSpaPO.getnQty() != null){
                                svcUploadCrmSpaPO.setnQty(svcUploadCrmSpaPO.getnQty().subtract(item.getnQty()));
                                svcUploadCrmSpaPO.updateById();
                            }
                        }
                    }

                }
            }else{
                DbUnionCommonDto db3 = new DbUnionCommonDto();
                db3.setQueryConditions("a.NMainID ", 0, SVCServiceRequestVO.getiD());
                List<SVCServiceRequestSpaDTO> svcServiceRequestSpaDTOS = this.svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(db3);
                List<SVCServiceRequestSpaDTO> deleteItems = new ArrayList<>();
                for (SVCServiceRequestSpaDTO item:itemList
                     ) {
                    if (!StringUtils.isNullOrEmpty(item.getvSpa())){
                        item.setCrmSpaStatus("D");
                        deleteItems.add(item);
                    }
                }
                svcServiceRequestSpaDTOS.addAll(deleteItems);
                this.modifySaleOrder(SVCServiceRequestVO.getvObjectID().split(";")[1],svcServiceRequestSpaDTOS);
            }


            message.putMessage("SREMessage", "008");
            map.put("infor", message);
            map.put("isDelete", "1");
        }
        return map;
    }

    // 保存建议维修项目
    @Transactional
    @Override
    public Map<String, Object> dosavesugitem(DoSaveSugitIemVO doSaveSugitIemVO) {
        String resType = "1";
        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = doSaveSugitIemVO.getsVCServiceRequestVO();
        int isHasHistory = doSaveSugitIemVO.getIsHasHistory();
        List<SVCServiceRequestSugeestMitVO> list = doSaveSugitIemVO.getsVCServiceRequestSugeestMitVO();
        if (list != null && list.size() > 0) {

            for (SVCServiceRequestSugeestMitVO item : list) {
                if (StringUtils.isNullOrEmpty(item.getvItem())) {
                    message.putMessage("SVCMessage", "125", new String[]{"建议项目代码不可为空"});
                    map.put("err", message);
                    return map;
                }

                if (StringUtils.isNullOrEmpty(item.getvItemName())) {
                    message.putMessage("SVCMessage", "125", new String[]{"建议项目名称不可为空"});
                    map.put("err", message);
                    return map;
                }
                // 校验通过，执行更新
                SvcOrderSugeestMitPO po = new SvcOrderSugeestMitPO();
                BeanUtils.copyProperties(item, po);
                po.insertOrUpdate();

                SvcOrderSugeestMitDelPO delPO = new SvcOrderSugeestMitDelPO();
                QueryWrapper<SvcOrderSugeestMitDelPO> delQueryPo = new QueryWrapper<>();
                delQueryPo.eq("NMainID", po.getnMainID());
                delQueryPo.eq("VItem", po.getvItem());
                delQueryPo.eq("NDID", po.getnDID());
                List<SvcOrderSugeestMitDelPO> listdelpo = delPO.selectList(delQueryPo);
                if (listdelpo != null && listdelpo.size() > 0) {
                    BeanUtils.copyProperties(listdelpo.get(0), delPO);
                    delPO.deleteById();
                }
            }
        }
        // 建议维修项目
        List<SVCServiceRequestSugeestMitVO> SelfGetSugItemByMainID =
                svc0101_04Service.SelfGetSugItemByMainID(
                        SVCServiceRequestVO.getiD(), SVCServiceRequestVO.getvVin(), isHasHistory);
        map.put("sVCServiceRequestSugeestMitVO", SelfGetSugItemByMainID);
        map.put("resType", resType);

        return map;
    }

    // 删除建议项目
    @Transactional
    @Override
    public Map<String, Object> deletesugitem(DoSaveSugitIemVO doSaveSugitIemVO) {
        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = doSaveSugitIemVO.getsVCServiceRequestVO();
        List<SVCServiceRequestSugeestMitVO> itemList =
                doSaveSugitIemVO.getsVCServiceRequestSugeestMitVO();
        // 是否显示历史
        int isHasHistory = doSaveSugitIemVO.getIsHasHistory();

        if (itemList != null && itemList.size() > 0) {
            DbUnionCommonDto SVCVO = new DbUnionCommonDto();
            SVCVO.setQueryConditions("a.id", 0, SVCServiceRequestVO.getiD());
            List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
            if (list != null && list.size() > 0) {
                if (!"00".equals(list.get(0).getvRepairStatus())) {
                    // 委托书非在修状态，不可继续操作！
                    message.putMessage("SVCMessage", "077");
                    map.put("err", message);
                    return map;
                }
            }

            for (SVCServiceRequestSugeestMitVO item : itemList) {
                String id = item.getiD();
                if (!StringUtils.isNullOrEmpty(id)) {

                    SvcOrderSugeestMitPO po = new SvcOrderSugeestMitPO();
                    QueryWrapper<SvcOrderSugeestMitPO> queryitemPO = new QueryWrapper<>();
                    queryitemPO.eq("ID", item.getiD());
                    List<SvcOrderSugeestMitPO> listorderitem = po.selectList(queryitemPO);
                    if (listorderitem != null && listorderitem.size() > 0) {
                        // 删除时留下记录 原触发器功能
                        SvcOrderSugeestMitDelPO delPO = new SvcOrderSugeestMitDelPO();
                        BeanUtils.copyProperties(listorderitem.get(0), delPO);
                        delPO.insertOrUpdate();
                    }

                    po.deleteById(item.getiD());
                }
            }
            List<SVCServiceRequestSugeestMitVO> SelfGetSugItemByMainID =
                    svc0101_04Service.SelfGetSugItemByMainID(
                            SVCServiceRequestVO.getiD(), SVCServiceRequestVO.getvVin(), isHasHistory);
            map.put("sVCServiceRequestSugeestMitVO", SelfGetSugItemByMainID);
            map.put("isDelete", "1");
            // 删除成功
            message.putMessage("SREMessage", "008");
        }
        return map;
    }

    // 增加维修项目
    @Transactional
    @Override
    public Map<String, Object> additem(SvcServiceRequestViewDTO svcServiceRequestVO) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequestVO = svcServiceRequestVO;
        // 如果工时定额为空
        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnStdID())) {
            // 获取默认工时定额
            GetStdDTO serviceResult =
                    pucCommonService.GetStdBySaleTypeID(SVCServiceRequestVO.getnSaleTypeID());
            String stdId = serviceResult.getnStdID();
            if (!StringUtils.isNullOrEmpty(stdId)) {
                SVCServiceRequestVO.setnStdID(stdId);
            }
        }
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);

        // 获取维修项目
        List<SVCServiceRequestItemVODTO> itemList = SelfGetItemByMainID(SVCServiceRequestVO.getiD());
        if (itemList != null && itemList.size() > 0) {
            // 设置第一行选中
            map.put("sVCServiceRequestItemVO", itemList.get(0));
        }
        map.put("sVCServiceRequestItemTableVO", itemList);

        List<SVCServiceRequestSpaDTO> SpaList = SelfGetSPAByMainID(SVCServiceRequestVO.getiD());

        List<SVCServiceRequestToolVO> SptList = SelfGetToolByMainID(SVCServiceRequestVO.getiD());

        // 获取项目性质列表
        List<SVCItemKindSHVO> ItemKindlist =
                GetItemKindList(
                        SVCServiceRequestVO.getvSvcKind(),
                        "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                        SVCServiceRequestVO.getcFreeMaintain() + "",
                        SVCServiceRequestVO.getcExtraMaintain() + "");
        map.put("sVCItemKindSHVO", ItemKindlist);

        // 获取项目ID列表(已经存在的项目)
        List<SVCBatchSelectItemCM> ItemExitTable = new ArrayList<>();
        for (SVCServiceRequestItemVODTO ItemListSDO : itemList) {
            SVCBatchSelectItemCM NewItemSDO = new SVCBatchSelectItemCM();
            NewItemSDO.setiD(ItemListSDO.getnItemID());
            NewItemSDO.setvItem(ItemListSDO.getvItem());
            ItemExitTable.add(NewItemSDO);
        }
        map.put("itemExitTable", ItemExitTable);

        // 获取备件ID列表(已经存在的备件)
        List<SVCBatchSelectItemSPACM> SpaExitTable = new ArrayList<>();
        for (SVCServiceRequestSpaDTO SpaListSDO : SpaList) {
            SVCBatchSelectItemSPACM NewSpaSDO = new SVCBatchSelectItemSPACM();
            NewSpaSDO.setvModule(SpaListSDO.getvModule());
            NewSpaSDO.setvSpa(SpaListSDO.getvSpa());
            NewSpaSDO.setvSpaName(SpaListSDO.getvKindName());
            SpaExitTable.add(NewSpaSDO);
        }
        map.put("spaExitTable", SpaExitTable);

        // 获取工具ID列表(已经存在的工具)
        List<SVCBatchSelectItemSPTCM> SptExitTable = new ArrayList<>();
        for (SVCServiceRequestToolVO SptListSDO : SptList) {
            SVCBatchSelectItemSPTCM NewSptSDO = new SVCBatchSelectItemSPTCM();
            NewSptSDO.setnSptID(SptListSDO.getnToolID());
            NewSptSDO.setvSpt(SptListSDO.getvSpt());
            NewSptSDO.setvSptName(SptListSDO.getvSptName());
            SptExitTable.add(NewSptSDO);
        }
        map.put("sptExitTable", SptExitTable);

        return map;
    }

    // 批量增加维修项目
    @Transactional
    @Override
    public Map<String, Object> batchadditem(BatchAddItemVO batchAddItemVO) {

        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        SvcServiceRequestViewDTO SVCServiceRequestVO = new SvcServiceRequestViewDTO();
        // 维修项目列表 tt_svc_order_item
        List<SVCBatchSelectItemCM> ItemList = batchAddItemVO.getItemTable();
        // 预估备件 tt_svc_order_spa
        List<SVCBatchSelectItemSPACM> SpaList = batchAddItemVO.getSpaTable();
        // 建议维修项目 tt_svc_order_sugeest_mit
        List<SVCBatchSelectSuitItemCM> SuitItemTable = batchAddItemVO.getSuitItemTable();
        // 专用工具
        List<SVCBatchSelectItemSPTCM> SptList = batchAddItemVO.getSptTable();
        String NMainID = batchAddItemVO.getsVCServiceRequestVO_iD();

        String NStdID = UUID.randomUUID().toString();
        LocalDateTime now = LocalDateTime.now();

        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        SVCVO.setQueryConditions("a.iD", 0, NMainID);
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        if (list != null && list.size() > 0) {
            if (!"00".equals(list.get(0).getvRepairStatus())) {
                // 委托书非在修状态，不可执行操作！
                message.putMessage("SVCMessage", "077");
                map.put("err", message);
                return map;
            } else {
                SVCServiceRequestVO = list.get(0);
            }
        }
        // 季节活动
        List<String> suitIdList = new ArrayList<>();

        // 获取委托书工时定额nStdID用来比较项目 于炳森 2021-5-26
        String nStdID = "";
        if (!StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnStdID())) {
            nStdID = SVCServiceRequestVO.getnStdID();
        }

        // 校验并保存项目
        for (SVCBatchSelectItemCM SelectItem : ItemList) {
            // 校验是否存在重复项目
            if (!"ZJ990000".equals(SelectItem.getvVItem()) && !"padSugItem".equals(SelectItem.getvType())) {
                if (SelfIsExist("SVCServiceRequestItemVO", NMainID, "NItemID", SelectItem.getiD() + "")) {
                    message.putMessage(
                            "SVCMessage", "006", new String[]{"项目", SelectItem.getvItem()}); // {0}{1}已经存在!
                    map.put("err", message);
                    return map;
                }
            } else {
                String itemid = SelectItem.getvVItem();
                if (StringUtils.isNullOrEmpty(itemid)) {
                    itemid = "";
                }

                if (!StringUtils.isNullOrEmpty(itemid) && itemid.length() != 8 && !"ZJ99".equals(itemid.substring(0, 4))) {
                    message.putMessage(
                            "SVCMessage", "061", new String[]{SelectItem.getvItem()}); // 项目代码{0}不符合规则【ZJ99####】!
                    map.put("err", message);
                }

                if (SelfIsExist("SVCServiceRequestItemVO", NMainID, "VItem", SelectItem.getvItem())) {
                    message.putMessage(
                            "SVCMessage", "006", new String[]{"项目", SelectItem.getvItem()}); // {0}{1}已经存在!
                    map.put("err", message);
                    return map;
                }
            }

            // 委托书项目ID
            String nSvcItemID = UUID.randomUUID().toString();
            // 如果是季节性活动套餐，则委托书打季节活动标识
            if ("1".equals(SelectItem.getvItemType())) {
                DbUnionCommonDto searchEntity = new DbUnionCommonDto();
                searchEntity.setQueryConditions("a.ID ", 0, SelectItem.getiD());
                List<SVCMaintainSuitViewDTO> SVCMaintainSuitlist =
                        sVCMaintainSuitViewMapper.query(searchEntity);
                if (SVCMaintainSuitlist != null && SVCMaintainSuitlist.size() > 0) {
                    String cSeason = SVCMaintainSuitlist.get(0).getcSeason();
                    if ("1".equals(cSeason)) {
                        SVCServiceRequestVO.setcSeasonActive(1);
                    }
                }

            } else { // 如果项目是季节性活动套餐子项，委托书也打季节活动标识
                if (!StringUtils.isNullOrEmpty(SelectItem.getnSuitID())
                        && !suitIdList.contains(SelectItem.getnSuitID())) {
                    DbUnionCommonDto searchEntity = new DbUnionCommonDto();
                    searchEntity.setQueryConditions("a.ID ", 0, SelectItem.getnSuitID());
                    List<SVCMaintainSuitViewDTO> SVCMaintainSuitlist =
                            sVCMaintainSuitViewMapper.query(searchEntity);

                    if (SVCMaintainSuitlist != null && SVCMaintainSuitlist.size() > 0) {
                        String cSeason = SVCMaintainSuitlist.get(0).getcSeason();
                        if ("1".equals(cSeason)) {
                            SVCServiceRequestVO.setcSeasonActive(1);
                        }
                    }
                }
            }

            // 如果来自建议项目，更新建议项目使用标识
            if (!StringUtils.isNullOrEmpty(SelectItem.getnSugSvcBillID())) {

                DbUnionCommonDto getxm = new DbUnionCommonDto();
                getxm.setQueryConditions("a.nMainid", 0, SelectItem.getnSugSvcBillID());
                getxm.setQueryConditions("a.VItem", 0, SelectItem.getvItem());
                List<SVCServiceRequestSugeestMitVO> sugItemlist =
                        sVCGetSVCSugeestMitPRMapper.sVCGetSVCSugeestMitPRList(getxm);

                // 判断建议项目和委托书工时定额是否一致 于炳森 2021-5-26
                if (!StringUtils.isNullOrEmpty(nStdID) && !nStdID.equals(SelectItem.getnStdID())) {
                    message.putMessage("SVCMessage","0409",new String[] {"工时定额不一致，不允许添加"});
                }

                if (sugItemlist != null && sugItemlist.size() > 0) {
                    // 更新委托书建议维修项目 tt_svc_order_sugeest_mit
                    SvcOrderSugeestMitPO Sugeest = new SvcOrderSugeestMitPO();
                    QueryWrapper<SvcOrderSugeestMitPO> Sugeestquery = new QueryWrapper<>();
                    Sugeestquery.eq("id", sugItemlist.get(0).getiD());
                    List<SvcOrderSugeestMitPO> Sugeestlist = Sugeest.selectList(Sugeestquery);
                    SvcOrderSugeestMitPO updatesugeest = new SvcOrderSugeestMitPO();
                    BeanUtils.copyProperties(Sugeestlist.get(0), updatesugeest);
                    updatesugeest.setcUsed(1);
                    updatesugeest.setnCorBillID(SVCServiceRequestVO.getiD());
                    sugItemlist.get(0).setcUsed("1");
                    sugItemlist.get(0).setnCorBillID(SVCServiceRequestVO.getiD());
                    updatesugeest.updateById();
                    // 原触发器的功能
                    SvcOrderSugeestMitDelPO Sugeestdel = new SvcOrderSugeestMitDelPO();
                    QueryWrapper<SvcOrderSugeestMitDelPO> SugeestQuedel = new QueryWrapper<>();
                    SugeestQuedel.eq("NMainID", updatesugeest.getnMainID());
                    SugeestQuedel.eq("VItem", updatesugeest.getvItem());
                    SugeestQuedel.eq("NDID", updatesugeest.getnDID());
                    List<SvcOrderSugeestMitDelPO> SugeestdelList = Sugeestdel.selectList(SugeestQuedel);
                    if (SugeestdelList != null && SugeestdelList.size() > 0) {
                        BeanUtils.copyProperties(SugeestdelList.get(0), Sugeestdel);
                        Sugeestdel.deleteById();
                    }
                }
            }

            NStdID = SelectItem.getnStdID();
            SVCServiceRequestItemVO SVCServiceRequestItemVO = new SVCServiceRequestItemVO();

            SVCServiceRequestItemVO.setiD(nSvcItemID);
            SVCServiceRequestItemVO.setnMainID(NMainID);
            SVCServiceRequestItemVO.setnItemID(SelectItem.getiD());
            SVCServiceRequestItemVO.setvItem(SelectItem.getvItem());
            SVCServiceRequestItemVO.setvItemName(SelectItem.getvItemName());
            SVCServiceRequestItemVO.setvKind(SelectItem.getvKind());
            SVCServiceRequestItemVO.setvMainPart(SelectItem.getvMainPart());
            SVCServiceRequestItemVO.setnManhaurFee(SelectItem.getnManhaurFee());
            SVCServiceRequestItemVO.setnManhaur(SelectItem.getnManhaur());
            SVCServiceRequestItemVO.setvAdditionalDesc(SelectItem.getvAdditionalDesc());
            SVCServiceRequestItemVO.setnDID(userInfor.getnDID());
            SVCServiceRequestItemVO.setvItemProperty(SelectItem.getvItemType());
            SVCServiceRequestItemVO.setvUserCode(SelectItem.getvUserCode());
            SVCServiceRequestItemVO.setnSVCAdviserID(SelectItem.getnSVCAdviserID());
            SVCServiceRequestItemVO.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
            // SVCServiceRequestItemVO.setnRepairDuration(SelectItem.("NRepairDuration"));
            SVCServiceRequestItemVO.setcSpecialStation(SelectItem.getcSpecialStation() + "");
            SVCServiceRequestItemVO.setRecordVersion(SelectItem.getRecordVersion());
            SVCServiceRequestItemVO.setnVIPPackID(SelectItem.getnVIPPackID());
            SVCServiceRequestItemVO.setvOperateStatus("00");
            SVCServiceRequestItemVO.setvTeam(SelectItem.getvTeam());
            if (!StringUtils.isNullOrEmpty(SelectItem.getvTeam())) {
                DepartmentsPO bm = new DepartmentsPO();
                QueryWrapper<DepartmentsPO> query = new QueryWrapper<>();
                query.eq("NDID", userInfor.getnDID());
                query.eq("VOrg", SelectItem.getvTeam());
                List<DepartmentsPO> STMDepartmentsQAList = bm.selectList(query);

                if (STMDepartmentsQAList != null && STMDepartmentsQAList.size() > 0) {
                    SVCServiceRequestItemVO.setvRepairProperty(
                            STMDepartmentsQAList.get(0).getvServiceProperty());
                }
            }
            if ("1".equals(SelectItem.getvItemType())) {
                SVCServiceRequestItemVO.setnSuitID(SelectItem.getiD());
                // 保存套餐子项
                if (SuitItemTable != null && SuitItemTable.size() > 0) {
                    // 套餐项目信息 SVCMaintainSuitItemVO-->SVCMaintainSuitItemDTO
                    DbUnionCommonDto searchEntity = new DbUnionCommonDto();
                    searchEntity.setQueryConditions("a.NMainID", 0, SelectItem.getiD());
                    searchEntity.setQueryConditions("a.ndid", 0, userInfor.getnDID());
                    List<SVCMaintainSuitItemDTO> SVCMaintainSuitItemList =
                            sVCMaintainSuitItemDTOMapper.getSVCMaintainSuitItemList(searchEntity);
                    if (SVCMaintainSuitItemList != null && SVCMaintainSuitItemList.size() > 0) {
                        for (SVCMaintainSuitItemDTO SVCMaintainSuitItem : SVCMaintainSuitItemList) {
                            for (SVCBatchSelectSuitItemCM SuitItem : SuitItemTable) {
                                String SuitItemNSuitID = SuitItem.getnSuitID();
                                String SelectItemID = SelectItem.getiD();
                                String SVCMaintainSuitItemNItemID = SVCMaintainSuitItem.getnItemID();
                                String SuitItemID = SuitItem.getnItemID();
                                if (StringUtils.isNullOrEmpty(SuitItemID)) {
                                    SuitItemID = "";
                                }
                                if ((!StringUtils.isNullOrEmpty(SuitItemNSuitID)
                                        && SuitItemNSuitID.equals(SelectItemID)
                                        && (SuitItemID.equals(SVCMaintainSuitItemNItemID)))) {
                                    SvcOrderSuitItemPO SVCServiceRequestSuitItemVO = new SvcOrderSuitItemPO();

                                    SVCServiceRequestSuitItemVO.setnMainID(NMainID);
                                    SVCServiceRequestSuitItemVO.setnItemID(SelectItem.getiD());
                                    SVCServiceRequestSuitItemVO.setnSubItemID(SVCMaintainSuitItem.getnItemID());
                                    SVCServiceRequestSuitItemVO.setvSubItem(SVCMaintainSuitItem.getvItem());
                                    SVCServiceRequestSuitItemVO.setvSubItemName(SVCMaintainSuitItem.getvItemName());
                                    SVCServiceRequestSuitItemVO.setnManhaur(SVCMaintainSuitItem.getnManhaur());
                                    SVCServiceRequestSuitItemVO.setnManhaurFee(SVCMaintainSuitItem.getnManhaurFee());
                                    SVCServiceRequestSuitItemVO.setnDID(userInfor.getnDID());
                                    SVCServiceRequestSuitItemVO.insertOrUpdate();

                                    break;
                                }
                            }
                        }
                    }
                }
            } else {
                SVCServiceRequestItemVO.setnSuitID(SelectItem.getnSuitID());
            }
            // 获取当前项目默认工时优惠率 currentManhourDisRate
            BigDecimal currentManhourDisRate =
                    getCurrentDefultCutRate(SVCServiceRequestItemVO, SVCServiceRequestVO);
            SVCServiceRequestItemVO.setnManhaurDisRate(currentManhourDisRate);
            logger.info("获取当前项目最大优惠率:{}", currentManhourDisRate
            );
            SvcOrderItemPO itmePO = new SvcOrderItemPO();
            BeanUtils.copyProperties(SVCServiceRequestItemVO, itmePO);

            itmePO.insertOrUpdate();


            //给小程序同步项目信息
            svcToSanyAppService.sendItemInfoToSanyApp(itmePO);
            // 原触发器的功能
            SvcOrderItemDelPO Itemdel = new SvcOrderItemDelPO();
            QueryWrapper<SvcOrderItemDelPO> SugeestQuedel = new QueryWrapper<>();
            SugeestQuedel.eq("NMainID", itmePO.getnMainID());
            SugeestQuedel.eq("VItem", itmePO.getvItem());
            SugeestQuedel.eq("NDID", itmePO.getnDID());
            List<SvcOrderItemDelPO> SugeestdelList = Itemdel.selectList(SugeestQuedel);
            if (SugeestdelList != null && SugeestdelList.size() > 0) {
                BeanUtils.copyProperties(SugeestdelList.get(0), Itemdel);
                Itemdel.deleteById();
            }
        }

        // 反写主表NStdID
        if (ItemList != null && ItemList.size() > 0) {
            SVCServiceRequestVO.setnStdID(NStdID);
        }
        if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnMaintain() + "")) {
            SVCServiceRequestVO.setnMaintain(0);
        }
        // 计算维修时长合计 透明车间的不要了
        SvcOrderPO SVCPO = new SvcOrderPO();
        BeanUtils.copyProperties(SVCServiceRequestVO, SVCPO);
        SVCPO.updateById();
        SVCServiceRequestVO.setRecordVersion(SVCPO.getRecordVersion());
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);

        // 校验并保存备件
        for (SVCBatchSelectItemSPACM SelectSpa : SpaList) {
            // 校验是否存在重复项目
            if (SelfIsExist(
                    "SVCServiceRequestSpaVO",
                    NMainID,
                    "vspa-|vMoudle",
                    SelectSpa.getvSpa() + "@" + SelectSpa.getvModule())) {
                message.putMessage(
                        "SVCMessage", "006", new String[]{"备件", SelectSpa.getvSpa()}); // {0}{1}已经存在!
                map.put("err", message);
                return map;
            }

            SvcOrderSpaPO SVCServiceRequestSpa = new SvcOrderSpaPO();

            SVCServiceRequestSpa.setnMainID(NMainID);
            SVCServiceRequestSpa.setvModule(SelectSpa.getvModule());
            SVCServiceRequestSpa.setnQty(SelectSpa.getnQty());
            SVCServiceRequestSpa.setnDID(userInfor.getnDID());
            SVCServiceRequestSpa.setvSpa(SelectSpa.getvSpa());
            SVCServiceRequestSpa.setvSpaAlias(SelectSpa.getvSpaName());
            SVCServiceRequestSpa.setvKind(SelectSpa.getvKind());
            SVCServiceRequestSpa.setnPrice(SelectSpa.getnPrice());
            SVCServiceRequestSpa.setdOut(now);
            SVCServiceRequestSpa.setvWorkProp(SVCServiceRequestVO.getvSvcKind());
            SVCServiceRequestSpa.setRecordVersion(
                    SelectSpa.getRecordVersion() == null ? 0 : SelectSpa.getRecordVersion());
            SVCServiceRequestSpa.setnVIPPackID(SelectSpa.getnVIPPackID());

            DbUnionCommonDto SPTMainSearchDto3 = new DbUnionCommonDto();
            SPTMainSearchDto3.setQueryConditions("b.vspa", 0, SelectSpa.getvSpa());
            SPTMainSearchDto3.setQueryConditions("b.vmodule", 0, SelectSpa.getvModule());
            SPTMainSearchDto3.setQueryConditions(
                    "b.ndid", 8, userInfor.getnDID() + "," + userInfor.getnCustGroupId());
            Map<String, String> para = new HashMap<String, String>();
            para.put("nDID_P", userInfor.getnDID());
            List<SPAMasterDataAllDTO> SPAMasterDataAllList =
                    spaMasterDataAll.SPAMasterDataAll(para, SPTMainSearchDto3);

            if (SPAMasterDataAllList != null && SPAMasterDataAllList.size() > 0) {
                if ("1".equals(SPAMasterDataAllList.get(0).getcMfr())) {
                    SVCServiceRequestSpa.setvChannel("01");
                } else {
                    SVCServiceRequestSpa.setvChannel("02");
                }
            }
            SVCServiceRequestSpa.insertOrUpdate();
        }

        map = GetDetailList(SVCServiceRequestVO);
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);

        return map;
    }

    Map<String, Object> GetDetailList(SvcServiceRequestViewDTO SVCServiceRequestVO) {
        Map<String, Object> map = new HashMap<>();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SDO = SVCServiceRequestVO;
        // 获取项目性质列表

        List<SVCItemKindSHVO> ItemKindlist =
                GetItemKindList(
                        SVCServiceRequestVO.getvSvcKind(),
                        "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                        SVCServiceRequestVO.getcFreeMaintain() + "",
                        SVCServiceRequestVO.getcExtraMaintain() + "");

        // 获取明细列表
        String ID = SDO.getiD();
        // 获取维修项目
        List<SVCServiceRequestItemVODTO> ItemList = SelfGetItemByMainID(ID);
        // 获取预估备件
        List<SVCServiceRequestSpaDTO> SpaList = SelfGetSPAByMainID(ID);
        // 获取专用工具
        List<SVCServiceRequestToolVO> SptList = SelfGetToolByMainID(ID);

        // 获取项目ID列表(已经存在的项目)
        List<SVCBatchSelectItemCM> ItemExitTable = new ArrayList<>();
        for (SVCServiceRequestItemVODTO ItemListSDO : ItemList) {
            SVCBatchSelectItemCM NewItemSDO = new SVCBatchSelectItemCM();
            NewItemSDO.setiD(ItemListSDO.getnItemID());
            NewItemSDO.setvItem(ItemListSDO.getvItem());
            ItemExitTable.add(NewItemSDO);
        }

        // 获取备件ID列表(已经存在的备件)
        List<SVCBatchSelectItemSPACM> SpaExitTable = new ArrayList<>();
        for (SVCServiceRequestSpaDTO SpaListSDO : SpaList) {
            SVCBatchSelectItemSPACM NewSpaSDO = new SVCBatchSelectItemSPACM();
            NewSpaSDO.setvModule(SpaListSDO.getvModule());
            NewSpaSDO.setvSpa(SpaListSDO.getvSpa());
            NewSpaSDO.setvSpaName(SpaListSDO.getvKindName());
            SpaExitTable.add(NewSpaSDO);
        }
        // 获取工具ID列表(已经存在的工具)
        List<SVCBatchSelectItemSPTCM> SptExitTable = new ArrayList<>();
        for (SVCServiceRequestToolVO SptListSDO : SptList) {
            SVCBatchSelectItemSPTCM NewSptSDO = new SVCBatchSelectItemSPTCM();
            NewSptSDO.setnSptID(SptListSDO.getnToolID());
            NewSptSDO.setvSpt(SptListSDO.getvSpt());
            NewSptSDO.setvSptName(SptListSDO.getvSptName());
            SptExitTable.add(NewSptSDO);
        }
        map.put("sVCItemKindSHVO", ItemKindlist);
        map.put("sVCServiceRequestItemTableVO", ItemList);
        if (ItemList != null && ItemList.size() > 0) {
            // 设置第一行选中
            map.put("sVCServiceRequestItemVO", ItemList.get(0));
        }
        map.put("sVCServiceRequestSpaVO", SpaList);
        map.put("sVCServiceRequestToolVO", SptList);
        map.put("itemExitTable", ItemExitTable);
        map.put("spaExitTable", SpaExitTable);
        map.put("sptExitTable", SptExitTable);

        return map;
    }

    // 保存维修项目
    @Transactional
    @Override
    public Map<String, Object> saveitem(SaveItemVO saveItemVO) {
        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = saveItemVO.getsVCServiceRequestVO();
        List<SVCServiceRequestItemVODTO> SVCServiceRequestItemTableVO =
                saveItemVO.getsVCServiceRequestItemVO();
        String NoShowMessage = saveItemVO.getNoShowMessage();
        Boolean isShowMessage = true;
        if ("1".equals(NoShowMessage)) {
            isShowMessage = true;
        }
        map.put("isPrintSave", "0");
        // 送修日期
        LocalDateTime dEnter = SVCServiceRequestVO.getdEnter();
        // 预计维修时间
        LocalDateTime dEstimateRepair = SVCServiceRequestVO.getdEstimateRepair();
        // 约定交车时间
        LocalDateTime dPromiseFinish = SVCServiceRequestVO.getdPromiseFinish();
        if (dPromiseFinish.isBefore(dEnter)) {
            // 预计维修时间不可小于接车时间!
            message.putMessage("SVCMessage", "051", new String[]{"预计维修时间", "送修日期"});
            map.put("err", message);
            return map;
        }
        if (dPromiseFinish.isBefore(dEstimateRepair)) {
            // 约定交车时间不可小于预计维修时间!
            message.putMessage("SVCMessage", "051", new String[]{"约定交车时间", "预计维修时间"});
            return map;
        }
        // 如果获取到了维修项目
        if (SVCServiceRequestItemTableVO != null && SVCServiceRequestItemTableVO.size() > 0) {
            for (SVCServiceRequestItemVODTO SVCServiceRequestItemVO : SVCServiceRequestItemTableVO) {

                // 开始日期
                LocalDateTime dBegin = SVCServiceRequestItemVO.getdBegin();
                // 完工日期
                LocalDateTime dFinish = SVCServiceRequestItemVO.getdFinish();
                if (dFinish.isBefore(dBegin)) {
                    // 完工日期不可小于开始日期!
                    message.putMessage("SVCMessage", "051", new String[]{"完工日期", "开始日期"});
                    return map;
                }

                if (SVCServiceRequestItemVO.getnManhaur() == null) {
                    SVCServiceRequestItemVO.setnManhaur(BigDecimal.ZERO);
                }

                if (SVCServiceRequestItemVO.getnManhaurFee() == null) {
                    SVCServiceRequestItemVO.setnManhaurFee(BigDecimal.ZERO);
                }
                SVCServiceRequestItemVO svcServiceRequestItem = new SVCServiceRequestItemVO();
                BeanUtils.copyProperties(SVCServiceRequestItemVO, svcServiceRequestItem);
                // 获取当前项目默认工时优惠率 currentManhourDisRate
                BigDecimal currentManhourDisRate =
                        getCurrentDefultCutRate(svcServiceRequestItem, SVCServiceRequestVO);
                SVCServiceRequestItemVO.setnManhaurDisRate(currentManhourDisRate);
                logger.info("获取当前项目最大优惠率:{}", currentManhourDisRate);

                        // 保存维修项目
                SvcOrderItemPO po = new SvcOrderItemPO();
                BeanUtils.copyProperties(SVCServiceRequestItemVO, po);
                po.insertOrUpdate();
                SvcOrderItemDelPO delPO = new SvcOrderItemDelPO();
                QueryWrapper<SvcOrderItemDelPO> delQueryPo = new QueryWrapper<>();
                delQueryPo.eq("NMainID", po.getnMainID());
                delQueryPo.eq("VItem", po.getvItem());
                delQueryPo.eq("NDID", po.getnDID());
                List<SvcOrderItemDelPO> listdelpo = delPO.selectList(delQueryPo);
                if (listdelpo != null && listdelpo.size() > 0) {
                    BeanUtils.copyProperties(listdelpo.get(0), delPO);
                    delPO.deleteById();
                }

                // 回传版本号
                SVCServiceRequestItemVO.setRecordVersion(po.getRecordVersion());
                map.put("sVCServiceRequestItemVO", SVCServiceRequestItemVO);
            }
        }

        // 计算维修时长合计
        SVCServiceRequestVO.setnSumRepairTime(
                CulcuSumRepairDuration(SVCServiceRequestVO.getiD(), SVCServiceRequestVO.getnDID()));
        // 保存委托书
        SvcOrderPO svcpo = new SvcOrderPO();
        QueryWrapper<SvcOrderPO> query = new QueryWrapper<>();
        query.eq("id", SVCServiceRequestVO.getiD());
        List<SvcOrderPO> listSVCPO = svcpo.selectList(query);
        BeanUtils.copyProperties(listSVCPO.get(0), svcpo);
        // 防止多次保存，版本号报错，故而重新查询赋值再保存
        svcpo.setnSumRepairTime(SVCServiceRequestVO.getnSumRepairTime());
        svcpo.updateById();
        SVCServiceRequestVO.setRecordVersion(svcpo.getRecordVersion());
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        if (isShowMessage) {
            message.putMessage("SREMessage", "009");
            map.put("infor", message);
        }
        map.put("isPrintSave", "1");
        return map;
    }

    // 保存专用工具
    @Override
    @Transactional
    public Map<String, Object> batchsavetool(BatchSaveToolVO batchSaveToolVO) {

        Map<String, Object> map = new HashMap<>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = batchSaveToolVO.getsVCServiceRequestVO();
        List<SVCServiceRequestToolVO> ToolList = batchSaveToolVO.getsVCServiceRequestToolVO();
        // 保存时获取委托书ID
        String NMainID = SVCServiceRequestVO.getiD();
        if (null != ToolList) {
            for (SVCServiceRequestToolVO Tool : ToolList) {

                String id = Tool.getiD();
                // 插入
                if (StringUtils.isNullOrEmpty(id)) {
                    if (SelfIsExist("SVCServiceRequestToolVO", NMainID, "NToolID", Tool.getnToolID())) {
                        message.putMessage(
                                "SVCMessage", "006", new String[]{"工具", Tool.getvSpt()}); // {0}{1}已经存在!
                        map.put("err", message);
                        return map;
                    }
                    SVCServiceRequestToolVO SVCServiceRequestToolVO = new SVCServiceRequestToolVO();
                    SVCServiceRequestToolVO.setiD(UUID.randomUUID().toString());
                    SVCServiceRequestToolVO.setnMainID(NMainID);
                    SVCServiceRequestToolVO.setnToolID(Tool.getnToolID());
                    SVCServiceRequestToolVO.setnQty(Tool.getnQty());
                    SVCServiceRequestToolVO.setnDID(SVCServiceRequestVO.getnDID());
                    BigDecimal toolqty = Tool.getnQty();
                    if (toolqty != null && toolqty.compareTo(Tool.getnQtyForUse()) > 0) {
                        SVCServiceRequestToolVO.setcShort(1);
                    } else {
                        SVCServiceRequestToolVO.setcShort(0);
                    }
                    SvcOrderToolPO po = new SvcOrderToolPO();
                    BeanUtils.copyProperties(SVCServiceRequestToolVO, po);
                    po.insert();

                    /******************20201201逄海 增加工具记录重要操作日志**************************/
                    //取得工具名称
                    String vSvcToolSptName = "";
                    SptMasterDataPO sptMasterDataPO = new SptMasterDataPO();
                    sptMasterDataPO.setiD(po.getnToolID());
                    sptMasterDataPO = sptMasterDataPO.selectById();
                    if (sptMasterDataPO != null && !com.vw.mep.dms.function.StringUtils.isNullOrEmptyByUUid(sptMasterDataPO.getiD())) {
                        vSvcToolSptName = sptMasterDataPO.getvSptName();
                    }

                    DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
                    SysTemOtherLogPO LogPO = new SysTemOtherLogPO();
                    LogPO.setId(UUID.randomUUID().toString());
                    LogPO.setVType("ChgBill");
                    LogPO.setDCreate(LocalDateTime.now());
                    LogPO.setDImp(LocalDateTime.now());
                    LogPO.setVTrans("SVC0101_tool");
                    LogPO.setVContent("委托书【" + SVCServiceRequestVO.getvBillNO() + "】需要专用工具【" + vSvcToolSptName + "】的数量为" + po.getnQty().toString() + "，请提前做好准备工作！");
                    LogPO.setVEntity("SvcOrderToolPO");
                    LogPO.setNdid(userInfor.getnDID());
                    LogPO.setNbid(userInfor.getnBID());
                    LogPO.setNOprID(userInfor.getiD());
                    LogPO.setVOpr(userInfor.getvPerson());
                    LogPO.setVOprName(userInfor.getvPersonName());
                    LogPO.insertOrUpdate();
                    /******************20201201逄海 增加工具记录重要操作日志**************************/
                } else {
                    // 更新
                    SvcOrderToolPO po = new SvcOrderToolPO();
                    BeanUtils.copyProperties(Tool, po);
                    po.updateById();
                }
            }
        }
        // 校验并保存项目


        // 获取专用工具
        List<SVCServiceRequestToolVO> toolList = SelfGetToolByMainID(SVCServiceRequestVO.getiD());
        map.put("sVCServiceRequestToolVO", toolList);
        message.putMessage("SVCMessage", "005");
        map.put("infor", message);
        map.put("resType", "1");
        return map;
    }

    // 删除工具
    @Override
    public Map<String, Object> deletetool(BatchSaveToolVO batchSaveToolVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        SvcServiceRequestViewDTO SVCServiceRequestVO = batchSaveToolVO.getsVCServiceRequestVO();
        List<SVCServiceRequestToolVO> toolList = batchSaveToolVO.getsVCServiceRequestToolVO();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        if (toolList != null && toolList.size() > 0) {
            DbUnionCommonDto SVCVO = new DbUnionCommonDto();
            SVCVO.setQueryConditions("a.iD", 0, SVCServiceRequestVO.getiD());
            List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
            if (list != null && list.size() > 0) {
                if (!"00".equals(list.get(0).getvRepairStatus())) {
                    // 委托书非在修状态，不可继续操作！
                    message.putMessage("SVCMessage", "077");
                    map.put("err", message);
                    return map;
                }
            }

            for (SVCServiceRequestToolVO item : toolList) {
                String id = item.getiD();
                if (!StringUtils.isNullOrEmpty(id)) {
                    SvcOrderToolPO po = new SvcOrderToolPO();
                    po.deleteById(id);
                }
            }

            // 获取专用工具
            List<SVCServiceRequestToolVO> rtnList = SelfGetToolByMainID(toolList.get(0).getiD());
            map.put("sVCServiceRequestToolVO", rtnList);

            // 删除成功
            message.putMessage("SREMessage", "008");
            map.put("infor", message);
        }


        return map;
    }

    // 新建委托书
    @Override
    public Map<String, Object> add(SVCServiceRequest sVCServiceRequest) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SvcServiceRequestViewDTO SVCServiceRequestVO = new SvcServiceRequestViewDTO();
        SVCServiceRequest SVCServiceRequest = sVCServiceRequest;
        String nCusID = SVCServiceRequest.getvCus();
        // String nLkID = SVCServiceRequest.getnLkID();
        String vLkMobile = SVCServiceRequest.getvLkMobile();
        String vVin = SVCServiceRequest.getvVin();
        String vSvcFrom = SVCServiceRequest.getvSvcFrom();
        String nFromID = SVCServiceRequest.getnSvcFromBillID();
        String vSvcKind = SVCServiceRequest.getvSvcKind();
        String VUpgradeNO = SVCServiceRequest.getvUpgradeNO();
        String vClmMustID = SVCServiceRequest.getvClmMustID();
        String vRecallCode = SVCServiceRequest.getvRecallCode();
        String vRecallType = SVCServiceRequest.getvRecallType();
        String vSVCServiceRequest = SVCServiceRequest.getvRecallMessage();

        SVCServiceRequestVO.setvUpgradeNO(VUpgradeNO);
        SVCServiceRequestVO.setvQueryState(vRecallType);
        SVCServiceRequestVO.setvQueryStateDesc(vSVCServiceRequest);
        SVCServiceRequestVO.setvOpr(userInfor.getvPerson());
        SVCServiceRequestVO.setvOprname(userInfor.getvPersonName());

        // servicekey 用的大众没有
        // LocalDateTime dPickUp = SVCServiceRequest.getdPickUp();
        // sVCServiceRequestVO.setdPickUp(dPickUp);
        // 设置数据字典
        Map<String, Object> map = SetEnterDict(userInfor.getnDID());

        // 来源信息
        // 来源于档案
        if ("2".equals(vSvcFrom)) {
            SVCServiceRequestVO = GetNormalCusVin(nCusID, vLkMobile, vVin, SVCServiceRequestVO);
        }
        // 来源于预约单
        else if ("0".equals(vSvcFrom)) {
            SVCServiceRequestVO = GetNormalCusVin(nCusID, vLkMobile, vVin, SVCServiceRequestVO);

            // 更新预约单
            DbUnionCommonDto view = new DbUnionCommonDto();
            view.setQueryConditions("a.iD", 0, sVCServiceRequest.getnSvcFromBillID());
            List<SVCBookRegisterVO> bookList = null;
            if (!StringUtils.isNullOrEmpty(sVCServiceRequest.getnSvcFromBillID())) {
                bookList = sVCBookRegisterVOMapper.sVCBookRegisterVO(view, userInfor.getnDID());
            }


            if (bookList != null && bookList.size() > 0) {
                SVCServiceRequestVO.setdPickUp(bookList.get(0).getdMeatingCar());
                SVCServiceRequestVO.setdEstimateRepair(bookList.get(0).getdRepairBegin());
                SVCServiceRequestVO.setdPromiseFinish(bookList.get(0).getdHandCar());
                SVCServiceRequestVO.setnStdID(bookList.get(0).getnStdID());
                SVCServiceRequestVO.setnMileage(BigDecimal.valueOf(bookList.get(0).getnMileage()));
                SVCServiceRequestVO.setvLkName(bookList.get(0).getvLinkman());
                SVCServiceRequestVO.setvLkMobile(bookList.get(0).getvLKMobile());
                if (!StringUtils.isNullOrEmpty(bookList.get(0).getDeviceDesc())){
                    SVCServiceRequestVO.setDeviceDesc(bookList.get(0).getDeviceDesc());
                }
                SVCServiceRequestVO.setRunTimes(bookList.get(0).getRunTimes());
                SVCServiceRequestVO.setVolume(bookList.get(0).getVolume());
                SVCServiceRequestVO.setVolvo(bookList.get(0).getVolvo());
//                SVCServiceRequestVO.setvCus(bookList.get(0).getvCus());
                SVCServiceRequestVO.setvLicenseTag(bookList.get(0).getvLicenseTag());
                SVCServiceRequestVO.setdLicense(bookList.get(0).getdLicense());
                if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(bookList.get(0).getvBelongService())){
                    SVCServiceEngineerPO svcServiceEngineerPO = new SVCServiceEngineerPO();
                    QueryWrapper<SVCServiceEngineerPO> svcServiceEngineerPOQueryWrapper = new QueryWrapper<>();
                    svcServiceEngineerPOQueryWrapper.eq("vperson",bookList.get(0).getvBelongService());
                    svcServiceEngineerPOQueryWrapper.eq("ndid",bookList.get(0).getnDID());
                    svcServiceEngineerPO = svcServiceEngineerPO.selectOne(svcServiceEngineerPOQueryWrapper);
                    if(svcServiceEngineerPO != null && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(svcServiceEngineerPO.getiD())){
                        SVCServiceRequestVO.setnSVCExcAdviserID(svcServiceEngineerPO.getiD());
                        SVCServiceRequestVO.setvPersonName(svcServiceEngineerPO.getvPersonName());
                        SVCServiceRequestVO.setvPerson(svcServiceEngineerPO.getvPerson());
                    }
                }else{
                    SVCServiceRequestVO.setnSVCExcAdviserID("");
                    SVCServiceRequestVO.setvPersonName("");
                    SVCServiceRequestVO.setvPerson("");
                }
                if(!StringUtils.isNullOrEmpty(bookList.get(0).getvFromID())){
                    //去预约线索CRM订单号
                    SvcOnlineBookPO svcOnlineBookPO = new SvcOnlineBookPO();
                    svcOnlineBookPO.setiD(bookList.get(0).getvFromID());
                    svcOnlineBookPO = svcOnlineBookPO.selectById();
                    if (svcOnlineBookPO != null && !StringUtils.isNullOrEmpty(svcOnlineBookPO.getReservationOrder())){
                        SVCServiceRequestVO.setvObjectID(svcOnlineBookPO.getReservationOrder());
                        SVCServiceRequestVO.setvOrderType("01");
                    }
                }
            }
            map.put("isBook", "1");
        }
        // 来源于估算单
        else if ("1".equals(vSvcFrom)) {
            // 更新估算单
            DbUnionCommonDto query = new DbUnionCommonDto();
            query.setQueryConditions("a.ID", 0, nFromID);
            List<SVCEstimateViewDTO> estList = svc0201SvcEstimateMapper.sVCEstimateVO(query);

            SVCServiceRequestVO = GetNormalCusVin(nCusID, vLkMobile, vVin, SVCServiceRequestVO);

            if (estList != null && estList.size() > 0) {
                SVCServiceRequestVO.setnStdID(estList.get(0).getnStdID());
                SVCServiceRequestVO.setnMileage(estList.get(0).getnMileage());
                SVCServiceRequestVO.setvLkName(estList.get(0).getvLkName());
                SVCServiceRequestVO.setvLkMobile(estList.get(0).getvLkMobile());
                if (!StringUtils.isNullOrEmpty(estList.get(0).getDeviceDesc())){
                    SVCServiceRequestVO.setDeviceDesc(estList.get(0).getDeviceDesc());
                }
                SVCServiceRequestVO.setRunTimes(estList.get(0).getRunTimes());
                SVCServiceRequestVO.setVolume(estList.get(0).getVolume());
                SVCServiceRequestVO.setVolvo(estList.get(0).getVolvo());
                SVCServiceRequestVO.setvLicenseTag(estList.get(0).getvLicenseTag());
                SVCServiceRequestVO.setdLicense(estList.get(0).getdLicense());
                if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(estList.get(0).getvServiceEng())){
                    SVCServiceEngineerPO svcServiceEngineerPO = new SVCServiceEngineerPO();
                    QueryWrapper<SVCServiceEngineerPO> svcServiceEngineerPOQueryWrapper = new QueryWrapper<>();
                    svcServiceEngineerPOQueryWrapper.eq("vperson",estList.get(0).getvServiceEng());
                    svcServiceEngineerPOQueryWrapper.eq("ndid",estList.get(0).getnDID());
                    svcServiceEngineerPO = svcServiceEngineerPO.selectOne(svcServiceEngineerPOQueryWrapper);
                    if(svcServiceEngineerPO != null && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(svcServiceEngineerPO.getiD())){
                        SVCServiceRequestVO.setnSVCExcAdviserID(svcServiceEngineerPO.getiD());
                        SVCServiceRequestVO.setvPersonName(svcServiceEngineerPO.getvPersonName());
                        SVCServiceRequestVO.setvPerson(svcServiceEngineerPO.getvPerson());
                    }
                    else{
                        SVCServiceRequestVO.setnSVCExcAdviserID("");
                        SVCServiceRequestVO.setvPersonName("");
                        SVCServiceRequestVO.setvPerson("");
                    }
                }
                /********包工费，包工方式，施救费*******************/
                SVCServiceRequestVO.setvContractMode(estList.get(0).getvContractMode());
                SVCServiceRequestVO.setnContractFee(estList.get(0).getnContractFee());
                SVCServiceRequestVO.setnRescueFee(estList.get(0).getnRescueFee());
                /********包工费，包工方式，施救费*******************/
            }

            if (estList != null && estList.size() > 0) {
                SVCServiceRequestVO.setnStdID(estList.get(0).getnStdID());
                if("1".equals(estList.get(0).getvSvcFrom())){
                    map.put("isBook", "1");
                    //预约过来的单子查一下服务订单号
                    SvcBookRegisterPO svcBookRegisterPO = new SvcBookRegisterPO();
                    svcBookRegisterPO = svcBookRegisterPO.selectById(estList.get(0).getnSvcFromBillID());
                    if (svcBookRegisterPO != null && !StringUtils.isNullOrEmpty(svcBookRegisterPO.getvFromID())){
                        //去预约线索CRM订单号
                        SvcOnlineBookPO svcOnlineBookPO = new SvcOnlineBookPO();
                        svcOnlineBookPO.setiD(svcBookRegisterPO.getvFromID());
                        svcOnlineBookPO = svcOnlineBookPO.selectById();
                        if (svcOnlineBookPO != null && !StringUtils.isNullOrEmpty(svcOnlineBookPO.getReservationOrder())){
                            SVCServiceRequestVO.setvObjectID(svcOnlineBookPO.getReservationOrder());
                            SVCServiceRequestVO.setvOrderType("01");
                        }
                    }

                }
            }

        } else if ("3".equals(vSvcFrom)) {
            // 来源于接车单
            SVCServiceRequestVO = GetNormalCusVin(nCusID, vLkMobile, vVin, SVCServiceRequestVO);
            // 获取接车单信息
            DbUnionCommonDto takeCarConditions = new DbUnionCommonDto();
            takeCarConditions.setQueryConditions("a.iD", 0, nFromID);
            SvcTakeCarDTO takeCarInfo = svcTakeCarViewMapper.getSvcTakeCarInfo(takeCarConditions);


            SVCServiceRequestVO.setdPickUp(takeCarInfo.getdEnter());
//            SVCServiceRequestVO.setdEstimateRepair(takeCarInfo.getnEstimateTime());
//            SVCServiceRequestVO.setdPromiseFinish(takeCarInfo.getdpr);
            SVCServiceRequestVO.setnStdID(takeCarInfo.getnStdID());
            SVCServiceRequestVO.setnMileage(takeCarInfo.getnMileage());
            SVCServiceRequestVO.setvBreakdownDesc(takeCarInfo.getvBreakdownDesc());

        }

        // 设置委托书默认属性
        SVCServiceRequestVO =
                SetDefaultSvc(SVCServiceRequestVO, userInfor, vSvcKind, vSvcFrom, nFromID, now);

        //设置客户档案省市区县 小区

        // 查询客户档案填充省市区县 和客户详细地址
        // 增加省市区县list
        CustomerPO customerPO = new CustomerPO();
        QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vCus", SVCServiceRequestVO.getvCus());
        queryWrapper.eq("ndid", userInfor.getnDID());
        List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
        if (cuslistPO != null && cuslistPO.size() > 0) {
            customerPO = cuslistPO.get(0);
            List<STMCityVODTO> vCityLinklist = new ArrayList<>();
            vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
            SVCServiceRequestVO.setvCityLink(vCityLinklist);
            SVCServiceRequestVO.setvCusAddrDetail(customerPO.getvCusAddrDetail());
            String vAddrStr = customerPO.getvProvince() + "," + customerPO.getvCity() + "," + customerPO.getvArea() ;
            SVCServiceRequestVO.setvAddrSre(vAddrStr);
        }
        SVCServiceRequestVO.setvCusEvaClass("Z");
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);

        // 获取项目性质列表
        List<SVCItemKindSHVO> ItemKindlist =
                GetItemKindList(
                        SVCServiceRequestVO.getvSvcKind(),
                        "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                        SVCServiceRequestVO.getcFreeMaintain() + "",
                        SVCServiceRequestVO.getcExtraMaintain() + "");

        map.put("sVCItemKindSHVO", ItemKindlist);

        // 工时和工时费 允许负数
        String isAllowed = stmCommonService.GetParameters("IsAllowMinus", userInfor.getnBID(), "SVC");
        map.put("isAllowed", isAllowed);

        // CRMInsuranceVO 保险
        List<CRMInsuranceVODTO> CRMInsuranceList = getCRMInsuranceVO(userInfor.getnDID(), vVin);
        map.put("cRMInsuranceVO", CRMInsuranceList);

        /*********************20201125 逄海添加 返回值增加平均行驶里程服务参数**************************************************/
        String vStdDayMileage = stmCommonService.GetParameters("StdDayMileage", userInfor.getnDID(), "SVC");
        BigDecimal nStdDayMileage = new BigDecimal(vStdDayMileage);
        map.put("nStdDayMileage", nStdDayMileage);
        /*********************20201125 逄海添加 返回值增加平均行驶里程服务参数**************************************************/
        // 取得取送车服务
        String takeCarService =
                stmCommonService.GetParameters("TakeCarService", userInfor.getnBID(), "SVC");
        map.put("takeCarService", takeCarService);

        return map;
    }

    // 设置委托书默认属性
    @Override
    public SvcServiceRequestViewDTO SetDefaultSvc(
            SvcServiceRequestViewDTO SVCServiceRequestVO,
            DMSLoginInfoDto userInfor,
            String vSvcKind,
            String vSvcFrom,
            String nFromID,
            LocalDateTime now)
            throws Exception {

        SVCServiceRequestVO.setnDID(userInfor.getnDID());
        SVCServiceRequestVO.setdEnter(now);
        SVCServiceRequestVO.setvRepairStatus("00");
        if(com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvContractMode())){
            SVCServiceRequestVO.setvContractMode("00");
        }
        if(com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnContractFee())){
            SVCServiceRequestVO.setnContractFee(BigDecimal.ZERO);
        }
        if(com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(SVCServiceRequestVO.getnRescueFee())){
            SVCServiceRequestVO.setnRescueFee(BigDecimal.ZERO);
        }
        SVCServiceRequestVO.setnSumRepairTime(BigDecimal.ZERO);
        SVCServiceRequestVO.setnTrafficFee(BigDecimal.ZERO);
        SVCServiceRequestVO.setnNextMtMileage(BigDecimal.ZERO);
        SVCServiceRequestVO.setvSvcKind(vSvcKind);
        SVCServiceRequestVO.setvBillNO(vSvcKind + "-");
        SVCServiceRequestVO.setvSvcFrom(vSvcFrom);
        SVCServiceRequestVO.setnSvcFromBillID(nFromID);
        SVCServiceRequestVO.setvWarrantyState("1");
        SVCServiceRequestVO.setcWash(1);

        DbUnionCommonDto searchEntity6 = new DbUnionCommonDto();
        searchEntity6.setQueryConditions("userID", 0, userInfor.getiD());
        searchEntity6.setQueryConditions("ndid", 0, userInfor.getnDID());
        searchEntity6.setQueryConditions("vRole", 0, "ADVISER");
        List<SVC0401UserRoleDTO> isRole = svc0401SvcOrderMapper.sql(searchEntity6);

        if (isRole != null && isRole.size() > 0) {
            SVCServiceRequestVO.setnSVCAdviserID(userInfor.getiD());
            SVCServiceRequestVO.setAdviserPerson(userInfor.getvPerson());
            SVCServiceRequestVO.setAdviserPersonName(userInfor.getvPersonName());
        }

        // 设置时间，有取ServiceKey，没有则计算
        LocalDateTime dPickUp = SVCServiceRequestVO.getdPickUp();
        if (dPickUp == null
                || (dPickUp != null && dPickUp.isAfter(LocalDateTime.of(1900, 1, 1, 0, 0, 0)))) {
            dPickUp = GetPickUpBegin(now, SVCServiceRequestVO.getnDID());
            SVCServiceRequestVO.setdPickUp(dPickUp);
        } else {
            dPickUp = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        }

        LocalDateTime dRepair = GetRepairBegin(dPickUp, SVCServiceRequestVO.getnDID());
        SVCServiceRequestVO.setdEstimateRepair(dRepair);

        SVCServiceRequestVO = GetFinishBegin(SVCServiceRequestVO);
        LocalDateTime dLicense = LocalDateTime.of(1900, 1, 1, 0, 0, 0);
        String local = SVCServiceRequestVO.getdLicense() + "";
        if (!StringUtils.isNullOrEmpty(local)) {
            dLicense = SVCServiceRequestVO.getdEstimateRepair();
        }
        // 计算JD和IA标识
        JDIAResult serviceResult =
                pUCCommonService.getJDIA(SVCServiceRequestVO.getdLicense(), now, userInfor.getnBID());
        int cJD = serviceResult.getcJD();
        int cIA = serviceResult.getcIA();

        SVCServiceRequestVO.setcJD(cJD);
        SVCServiceRequestVO.setcIA(cIA);
        // 默认语音提醒
        //        String vYYTX = stmCommonService.GetParameters("YYTX", SVCServiceRequestVO.getnDID(),
        // "SVC");
        //        int cYYTX = 0;
        //        if (vYYTX == "1")
        //        {
        //            cYYTX = 1;
        //        }
        //        SVCServiceRequestVO.setcTelRemind(cYYTX);
        //        //默认短信提醒
        //        String vDXTX = stmCommonService.GetParameters("DXTX", SVCServiceRequestVO.getnDID(),
        // "SVC");
        //        int cDXTX = 0;
        //        if (vDXTX == "1")
        //        {
        //            cDXTX = 1;
        //        }
        // 洗车方式
        // String CXCFS = stmCommonService.GetParameters("CXCFS", SVCServiceRequestVO.getnDID(), "SVC");
        // SVCServiceRequestVO.setvWash(CXCFS);
        // SVCServiceRequestVO.setcSMSRemind(cDXTX);
        // 取服务业务配置数据，判断委托书类别是收费还是免费
        String isFree = "0";
        // SVCBusConfigVO--->对应SvcBusConfigDTO
        DbUnionCommonDto searchEntity5 = new DbUnionCommonDto();
        searchEntity5.setQueryConditions("a.NCusGroupID", 0, "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74");
        searchEntity5.setQueryConditions("a.VSvcCls", 0, SVCServiceRequestVO.getvSvcKind());
        List<SvcBusConfigPO> busList = sVCBusConfigMapper.getSvcBusConfigDTOList(searchEntity5);
        if (busList != null && busList.size() > 0) {
            for (SvcBusConfigPO bus : busList) {
                if ((!StringUtils.isNullOrEmpty(vSvcKind)) && vSvcKind.equals(bus.getvSvcCls())) {
                    // 收费类委托书，旧件带走默认勾选
                    SVCServiceRequestVO.setcTakeawayOld(1);
                    break;
                }
            }
        }
        if ("0".equals(vSvcKind) || "2".equals(vSvcKind)) {
            SVCServiceRequestVO.setcMaintain(1);
        }
        // 设置默认结算方式
        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("a.NDID", 0, userInfor.getnDID());
        List<StlSettlementTypeSHViewDTO> setTypeList =
                stlSettlementTypeSHViewMapper.query(dbUnionCommonDto);
        if (setTypeList != null && setTypeList.size() > 0) {
            SVCServiceRequestVO.setvSettleMode(setTypeList.get(0).getvSettlement());
        }

        return SVCServiceRequestVO;
    }

    // 获取交车开始时间
    private SvcServiceRequestViewDTO GetFinishBegin(SvcServiceRequestViewDTO SVCServiceRequestVO) {
        // 取系统参数 维修时长
        String vRepairTime =
                stmCommonService.GetParameters("NRepairTime", SVCServiceRequestVO.getnDID(), "SVC");
        BigDecimal nRepairTime = BigDecimal.ZERO;
        if (!StringUtils.isNullOrEmpty(vRepairTime)) {
            nRepairTime = new BigDecimal(vRepairTime);
        }

        LocalDateTime dPromiseFinish =
                SVCServiceRequestVO.getdEstimateRepair()
                        .plusHours(Long.parseLong(nRepairTime.add(BigDecimal.ONE) + ""));
        SVCServiceRequestVO.setdPromiseFinish(dPromiseFinish);
        SVCServiceRequestVO.setnRepairTime(nRepairTime);
        return SVCServiceRequestVO;
    }

    /// <summary>
    /// 计算维修时长合计
    /// </summary>
    @Override
    public BigDecimal CulcuSumRepairDuration(String nSvcID, String nDID) {
        BigDecimal nSumRepairDuration = BigDecimal.ZERO;
        List<SVCServiceRequestItemVODTO> rpItemList = SelfGetItemByMainID(nSvcID);
        // 一般项目 + 套项 + 套项下的附加项目，任意一项为0则全部为0
        if (rpItemList != null && rpItemList.size() > 0) {
            for (SVCServiceRequestItemVODTO item : rpItemList) {
                if (item.getnRepairDuration() != null && item.getnRepairDuration().compareTo(BigDecimal.ZERO) > 0) {
                    nSumRepairDuration = nSumRepairDuration.add(item.getnRepairDuration());
                } else {
                    nSumRepairDuration = BigDecimal.ZERO;
                    break;
                }
                // 套餐
                if ("1".equals(item.getvItemProperty())) {
                    // 套餐项目信息 SVCMaintainSuitItemVO-->SVCMaintainSuitItemDTO
                    DbUnionCommonDto searchEntity = new DbUnionCommonDto();
                    searchEntity.setQueryConditions("a.NMainID", 0, item.getnItemID());
                    searchEntity.setQueryConditions("a.NDID", 0, nDID);
                    List<SVCMaintainSuitItemDTO> resultList =
                            sVCMaintainSuitItemDTOMapper.getSVCMaintainSuitItemList(searchEntity);

                    if (resultList != null && resultList.size() > 0) {
                        Boolean isBreak = false;
                        for (SVCMaintainSuitItemDTO suitItem : resultList) {
                            // 如果是附加项目
                            if ("1".equals(suitItem.getcAdditional())) {
                                if (suitItem.getnRepairDuration().compareTo(BigDecimal.ZERO) > 0) {
                                    nSumRepairDuration = nSumRepairDuration.add(suitItem.getnRepairDuration());
                                } else {
                                    nSumRepairDuration = BigDecimal.ZERO;
                                    isBreak = true;
                                    break;
                                }
                            }
                        }
                        if (isBreak) {
                            break;
                        }
                    }
                }
            }
        }
        return nSumRepairDuration;
    }

    // 获取常规客户车辆信息
    public SvcServiceRequestViewDTO GetNormalCusVin(
            String vCus, String vLkMobile, String vVin, SvcServiceRequestViewDTO SVCServiceRequestVO) {

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        // 按ID查询客户档案
        if (!StringUtils.isNullOrEmpty(vCus)) {
            CustomerInfoVO customerInfoVO = new CustomerInfoVO();
            customerInfoVO.setvCus(vCus);
            customerInfoVO.setnDID(userInfor.getnDID());
            CustomerInfoVO cusList =
                    (CustomerInfoVO) svcToCrmService.getCustomer(customerInfoVO).getData();
            //            Map<String, String> cusList = (Map<String, String>)
            // archivesFeignClient.getCustomer(userInfor.getnDID(), customerInfoVO).getData();
            //            CustomerInfoVO cusList = response.getData();
            if (cusList != null) {
                // SVCServiceRequestVO.setnCusID(cusList.geti("ID"));
                SVCServiceRequestVO.setvCus(cusList.getvCus());
                SVCServiceRequestVO.setvCusName(cusList.getvCusName());
                SVCServiceRequestVO.setvCusMobile(cusList.getvMobile());
                SVCServiceRequestVO.setvCusTel(cusList.getvTel());
                SVCServiceRequestVO.setvClass(cusList.getvClass());
                SVCServiceRequestVO.setvCusAddr(cusList.getvCusAddr());
                SVCServiceRequestVO.setvCusEvaClass(cusList.getvCusEvaClass());
                SVCServiceRequestVO.setvConstractTime(cusList.getvConstractTime());
                SVCServiceRequestVO.setvConstractType(cusList.getvConstractType());
            }

            // 获取联系人档案 && !StringUtils.isNullOrEmpty(vLkMobile)
            if (!StringUtils.isNullOrEmpty(vCus)) {
                //                RelateInfoVO lkList= runLinService.getRelate(vCus, vLkMobile);
                LinkmanPO lkList = (LinkmanPO) svcToCrmService.getRelate(customerInfoVO).getData();

                //                Map<String, String> lkList = (Map<String, String>)
                // archivesFeignClient.getRelate(userInfor.getnDID(), customerInfoVO).getData();
                if (lkList != null) {
                    // SVCServiceRequestVO.setnLKID("NLKID", lkList.("ID"));
                    SVCServiceRequestVO.setvLkName(lkList.getvLkName());
                    SVCServiceRequestVO.setvLkTel(lkList.getvLkTel());
                    SVCServiceRequestVO.setvLkMobile(lkList.getvLkMobile());
                    SVCServiceRequestVO.setvConstractTime(lkList.getvFittelTime());
                    SVCServiceRequestVO.setvConstractType(lkList.getvLinkWay());
                    // SVCServiceRequestVO.setbImpLinkMan("BImpLinkMan", lkList.getb("BImpLinkMan"));
                }
            }

            DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
            dbUnionCommonDto.setQueryConditions("a.NDID", 0, userInfor.getnDID());
            dbUnionCommonDto.setQueryConditions("a.VVin", 0, vVin);
            List<CRMGetVehicleVODTO> vinList = cRMGetVehicleVOMapper.queryVin(dbUnionCommonDto);
            // 获取车辆档案
            if (vinList != null && vinList.size() > 0) {
                //查车辆服务工程师代码和名称
                if(!StringUtils.isNullOrEmpty(vinList.get(0).getnSVCExcAdviserID())){
                    SVCServiceEngineerPO svcServiceEngineerPO = new SVCServiceEngineerPO();
                    svcServiceEngineerPO = svcServiceEngineerPO.selectById(vinList.get(0).getnSVCExcAdviserID());
                    if (null != svcServiceEngineerPO && StringUtils.isNullOrEmpty(svcServiceEngineerPO.getiD())){
                        SVCServiceRequestVO.setnSVCAdviserID(svcServiceEngineerPO.getiD());
                        SVCServiceRequestVO.setvPerson(svcServiceEngineerPO.getvPerson());
                        SVCServiceRequestVO.setvPersonName(svcServiceEngineerPO.getvPersonName());
                    }
                }

                SVCServiceRequestVO.setvVin(vinList.get(0).getvVin());
                SVCServiceRequestVO.setnMileage(vinList.get(0).getnMileage());
                SVCServiceRequestVO.setnSaleTypeID(vinList.get(0).getnSaleTypeID());
                SVCServiceRequestVO.setvLicenseTag(vinList.get(0).getvLicenseTag());
                SVCServiceRequestVO.setdProd(vinList.get(0).getdProd());
                SVCServiceRequestVO.setnColorId(vinList.get(0).getnColorId());
                SVCServiceRequestVO.setvColor(vinList.get(0).getvColor());
                SVCServiceRequestVO.setvColorName(vinList.get(0).getvColorName());
                SVCServiceRequestVO.setvEngineNo(vinList.get(0).getvEngineNo());
                SVCServiceRequestVO.setnCusGrade(vinList.get(0).getnCusGrade());
                SVCServiceRequestVO.setdBuy(vinList.get(0).getdBuy());
                SVCServiceRequestVO.setdLicense(vinList.get(0).getdLicense());
                SVCServiceRequestVO.setnSVCExcAdviserID(vinList.get(0).getnSVCExcAdviserID());
                SVCServiceRequestVO.setvVehRemark(vinList.get(0).getvRemark());
                SVCServiceRequestVO.setnA3ID(vinList.get(0).getnA3ID());
                SVCServiceRequestVO.setvCarType(vinList.get(0).getvCarType());
                SVCServiceRequestVO.setVolvo(vinList.get(0).getVolvo());
                SVCServiceRequestVO.setDeviceDesc(vinList.get(0).getDeviceDesc());
                SVCServiceRequestVO.setVolume(vinList.get(0).getVolume());
                SVCServiceRequestVO.setRunTimes(vinList.get(0).getRunTimes());
                SVCServiceRequestVO.setcOwnSell(vinList.get(0).getcOwnSell());
                int secondhand = 0;
                if ("1".equals(vinList.get(0).getcSVCSecondhand())) {
                    secondhand = 1;
                }

                SVCServiceRequestVO.setcSVCSecondhand(secondhand);
                SVCServiceRequestVO.setnSalerID(vinList.get(0).getnSalerID());
                SVCServiceRequestVO.setcPreSecondHand(vinList.get(0).getRecordVersion());
                SVCServiceRequestVO.setvA6(vinList.get(0).getvA6());
                SVCServiceRequestVO.setvA6MC(vinList.get(0).getvA6MC());
//                SVCServiceRequestVO.setVolvo(vinList.get(0).getVolvo());
//                SVCServiceRequestVO.setDeviceDesc(vinList.get(0).getDeviceDesc());
                if (SVCServiceRequestVO.getvCus() != null && SVCServiceRequestVO.getvCus().contains("*")) {
                    SVCServiceRequestVO.setvCusName(vinList.get(0).getvCusName());
                    SVCServiceRequestVO.setvCusMobile(vinList.get(0).getvMobile());
                    SVCServiceRequestVO.setvCusTel(vinList.get(0).getvTel());
                    SVCServiceRequestVO.setvClass(vinList.get(0).getvClass());
                    SVCServiceRequestVO.setvCusEvaClass(vinList.get(0).getvCusEvaClass());
                    SVCServiceRequestVO.setvCusAddr(vinList.get(0).getvCusAddr());
                    SVCServiceRequestVO.setvLkName(vinList.get(0).getvLkName());
                    SVCServiceRequestVO.setvLkMobile(vinList.get(0).getvLkMobile());
                    SVCServiceRequestVO.setvLkTel(vinList.get(0).getvLkTel());
                }
                // 如果已经获取到车辆档案了，联系人信息从车辆档案获取
                String vlkID = vinList.get(0).getnLKID();
                if (!StringUtils.isNullOrEmpty(vlkID)) {
                    LinkmanPO linkmanPO = new LinkmanPO();
                    linkmanPO = linkmanPO.selectById(vlkID);
                    /****************20210301 panghai 修改联系人为空的情况****************************/
                    if (linkmanPO != null && !StringUtils.isNullOrEmpty(linkmanPO.getiD())) {
                        SVCServiceRequestVO.setvLkName(linkmanPO.getvLkName());
                        SVCServiceRequestVO.setvLkTel(linkmanPO.getvLkTel());
                        SVCServiceRequestVO.setvLkMobile(linkmanPO.getvLkMobile());
                        SVCServiceRequestVO.setvConstractTime(linkmanPO.getvFittelTime());
                        SVCServiceRequestVO.setvConstractType(linkmanPO.getvLinkWay());
                    }
                    /****************20210301 panghai 修改联系人为空的情况****************************/
                }


            } else {
                // 获取车辆信息
                DbUnionCommonDto getVehicleInfoVO = new DbUnionCommonDto();
                getVehicleInfoVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
                getVehicleInfoVO.setQueryConditions("a.vvin", 0, vVin);
                List<CRMSALGetVehicleInfoVODTO> vehInfoList =
                        crm0001Mapper.sALGetVehicleInfoVO(getVehicleInfoVO);
                if (vehInfoList != null && vehInfoList.size() > 0) {
                    SVCServiceRequestVO.setvVin(vehInfoList.get(0).getvVin());
                    SVCServiceRequestVO.setnMileage(BigDecimal.ZERO);
                    SVCServiceRequestVO.setnSaleTypeID(vehInfoList.get(0).getnSaleTypeID());
                    SVCServiceRequestVO.setdProd(vehInfoList.get(0).getdProd());
                    SVCServiceRequestVO.setnColorId(vehInfoList.get(0).getnColorID());
                    SVCServiceRequestVO.setvEngineNo(vehInfoList.get(0).getvEngineNo());
                    SVCServiceRequestVO.setvColor(vehInfoList.get(0).getvColor());
                    SVCServiceRequestVO.setvColorName(vehInfoList.get(0).getvColorName());
                    SVCServiceRequestVO.setVolvo(vehInfoList.get(0).getVolvo());
                    SVCServiceRequestVO.setDeviceDesc(vehInfoList.get(0).getDeviceDesc());
                    SVCServiceRequestVO.setVolume(vehInfoList.get(0).getVolume());
                    SVCServiceRequestVO.setRunTimes(vehInfoList.get(0).getRunTimes());
                    SVCServiceRequestVO.setcOwnSell(vehInfoList.get(0).getcOwnSell());
                }
            }
        }else{
            DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
            dbUnionCommonDto.setQueryConditions("a.NDID", 0, userInfor.getnDID());
            dbUnionCommonDto.setQueryConditions("a.VVin", 0, vVin);
            List<CRMGetVehicleVODTO> vinList = cRMGetVehicleVOMapper.queryVin(dbUnionCommonDto);
            // 获取车辆档案
            if (vinList != null && vinList.size() > 0) {
                //查车辆服务工程师代码和名称
                if(!StringUtils.isNullOrEmpty(vinList.get(0).getnSVCExcAdviserID())){
                    SVCServiceEngineerPO svcServiceEngineerPO = new SVCServiceEngineerPO();
                    svcServiceEngineerPO = svcServiceEngineerPO.selectById(vinList.get(0).getnSVCExcAdviserID());
                    if (null != svcServiceEngineerPO && StringUtils.isNullOrEmpty(svcServiceEngineerPO.getiD())){
                        SVCServiceRequestVO.setnSVCAdviserID(svcServiceEngineerPO.getiD());
                        SVCServiceRequestVO.setvPerson(svcServiceEngineerPO.getvPerson());
                        SVCServiceRequestVO.setvPersonName(svcServiceEngineerPO.getvPersonName());
                    }
                }
                SVCServiceRequestVO.setvCus(vinList.get(0).getvCus());
                SVCServiceRequestVO.setvVin(vinList.get(0).getvVin());
                SVCServiceRequestVO.setnMileage(vinList.get(0).getnMileage());
                SVCServiceRequestVO.setnSaleTypeID(vinList.get(0).getnSaleTypeID());
                SVCServiceRequestVO.setvLicenseTag(vinList.get(0).getvLicenseTag());
                SVCServiceRequestVO.setdProd(vinList.get(0).getdProd());
                SVCServiceRequestVO.setnColorId(vinList.get(0).getnColorId());
                SVCServiceRequestVO.setvColor(vinList.get(0).getvColor());
                SVCServiceRequestVO.setvColorName(vinList.get(0).getvColorName());
                SVCServiceRequestVO.setvEngineNo(vinList.get(0).getvEngineNo());
                SVCServiceRequestVO.setnCusGrade(vinList.get(0).getnCusGrade());
                SVCServiceRequestVO.setdBuy(vinList.get(0).getdBuy());
                SVCServiceRequestVO.setdLicense(vinList.get(0).getdLicense());
                SVCServiceRequestVO.setnSVCExcAdviserID(vinList.get(0).getnSVCExcAdviserID());
                SVCServiceRequestVO.setvVehRemark(vinList.get(0).getvRemark());
                SVCServiceRequestVO.setnA3ID(vinList.get(0).getnA3ID());
                SVCServiceRequestVO.setvCarType(vinList.get(0).getvCarType());
                SVCServiceRequestVO.setVolvo(vinList.get(0).getVolvo());
                SVCServiceRequestVO.setDeviceDesc(vinList.get(0).getDeviceDesc());
                SVCServiceRequestVO.setVolume(vinList.get(0).getVolume());
                SVCServiceRequestVO.setRunTimes(vinList.get(0).getRunTimes());
                SVCServiceRequestVO.setcOwnSell(vinList.get(0).getcOwnSell());
                int secondhand = 0;
                if ("1".equals(vinList.get(0).getcSVCSecondhand())) {
                    secondhand = 1;
                }

                SVCServiceRequestVO.setcSVCSecondhand(secondhand);
                SVCServiceRequestVO.setnSalerID(vinList.get(0).getnSalerID());
                SVCServiceRequestVO.setcPreSecondHand(vinList.get(0).getRecordVersion());
                SVCServiceRequestVO.setvA6(vinList.get(0).getvA6());
                SVCServiceRequestVO.setvA6MC(vinList.get(0).getvA6MC());
//                SVCServiceRequestVO.setVolvo(vinList.get(0).getVolvo());
//                SVCServiceRequestVO.setDeviceDesc(vinList.get(0).getDeviceDesc());
                if (StringUtils.isNullOrEmpty(SVCServiceRequestVO.getvCus()) && SVCServiceRequestVO.getvCus().contains("*")) {
                    SVCServiceRequestVO.setvCusName(vinList.get(0).getvCusName());
                    SVCServiceRequestVO.setvCusMobile(vinList.get(0).getvMobile());
                    SVCServiceRequestVO.setvCusTel(vinList.get(0).getvTel());
                    SVCServiceRequestVO.setvClass(vinList.get(0).getvClass());
                    SVCServiceRequestVO.setvCusEvaClass(vinList.get(0).getvCusEvaClass());
                    SVCServiceRequestVO.setvCusAddr(vinList.get(0).getvCusAddr());
                    SVCServiceRequestVO.setvLkName(vinList.get(0).getvLkName());
                    SVCServiceRequestVO.setvLkMobile(vinList.get(0).getvLkMobile());
                    SVCServiceRequestVO.setvLkTel(vinList.get(0).getvLkTel());
                }
                // 如果已经获取到车辆档案了，联系人信息从车辆档案获取
                String vlkID = vinList.get(0).getnLKID();
                if (!StringUtils.isNullOrEmpty(vlkID)) {
                    LinkmanPO linkmanPO = new LinkmanPO();
                    linkmanPO = linkmanPO.selectById(vlkID);
                    /****************20210301 panghai 修改联系人为空的情况****************************/
                    if (linkmanPO != null && !StringUtils.isNullOrEmpty(linkmanPO.getiD())) {
                        SVCServiceRequestVO.setvLkName(linkmanPO.getvLkName());
                        SVCServiceRequestVO.setvLkTel(linkmanPO.getvLkTel());
                        SVCServiceRequestVO.setvLkMobile(linkmanPO.getvLkMobile());
                        SVCServiceRequestVO.setvConstractTime(linkmanPO.getvFittelTime());
                        SVCServiceRequestVO.setvConstractType(linkmanPO.getvLinkWay());
                    }
                    /****************20210301 panghai 修改联系人为空的情况****************************/
                }

                CustomerInfoVO customerInfoVO = new CustomerInfoVO();
                customerInfoVO.setvCus(vCus);
                customerInfoVO.setnDID(userInfor.getnDID());
                CustomerInfoVO cusList =
                        (CustomerInfoVO) svcToCrmService.getCustomer(customerInfoVO).getData();
                //            Map<String, String> cusList = (Map<String, String>)
                // archivesFeignClient.getCustomer(userInfor.getnDID(), customerInfoVO).getData();
                //            CustomerInfoVO cusList = response.getData();
                if (cusList != null) {
                    // SVCServiceRequestVO.setnCusID(cusList.geti("ID"));
                    SVCServiceRequestVO.setvCus(cusList.getvCus());
                    SVCServiceRequestVO.setvConstractTime(cusList.getvConstractTime());
                    SVCServiceRequestVO.setvConstractType(cusList.getvConstractType());
                }

            }
        }

        /**************添加crm订单默认值*************************/
        String crmOrderType = stmCommonService.GetParameters("CRMORDERTYPE", userInfor.getnDID(), "SVC");
        SVCServiceRequestVO.setvOrderType(crmOrderType);
        /**************添加crm订单默认值*************************/
        return SVCServiceRequestVO;
    }

    /// <summary>
    /// 获取维修开始时间
    /// </summary>
    /// <param name="dPickUpBegin"></param>
    /// <returns></returns>
    public LocalDateTime GetRepairBegin(LocalDateTime dPickUpBegin, String nbid) {
        // 取系统参数 接车时长
        // 接车的默认时长**分钟
        String vPickUpTime = stmCommonService.GetParameters("PickUpTime", nbid, "SVC");
        BigDecimal nPickUpTime = BigDecimal.ZERO;

        if (!StringUtils.isNullOrEmpty(vPickUpTime)) {
            nPickUpTime = new BigDecimal(vPickUpTime);
        }
        Long longs = Long.parseLong(nPickUpTime.add(BigDecimal.ONE) + "");
        LocalDateTime dRepairBegin = dPickUpBegin.plusHours(longs);
        return dRepairBegin;
    }

    /// <summary>
    /// 获取接车结束时间
    /// </summary>
    /// <param name="dPickUpBegin"></param>
    /// <returns></returns>
    public LocalDateTime GetPickUpBegin(LocalDateTime dEnter, String nbid) {
        // 取系统参数 接车时长

        // 接车开始时间在送修时间前**分钟
        String vPickUpTime = stmCommonService.GetParameters("NJCKSSJ", nbid, "SVC");
        BigDecimal nPickUpTime = BigDecimal.ZERO;
        if (!StringUtils.isNullOrEmpty(vPickUpTime)) {
            nPickUpTime = new BigDecimal(vPickUpTime);
        }
        BigDecimal fuOne = new BigDecimal(-1);

        Long longs = Long.parseLong(nPickUpTime.multiply(fuOne) + "");
        LocalDateTime dPickUpBegin = dEnter.plusHours(longs);
        return dPickUpBegin;
    }

    // 校验委托书状态
    private Map<String, Object> CheckSvcBillState(String id) {
        Map<String, Object> map = new HashMap<>();
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, id);
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        if (list != null && list.size() > 0) {
            map.put("sVCServiceRequestVO", list.get(0));
            if (!"00".equals(list.get(0).getvRepairStatus())) {
                // 委托书非在修状态，不可继续操作！
                message.putMessage("SVCMessage", "077");
                map.put("err", message);
                return map;
            }
            if (list.get(0).getcDelete() == 1) {
                // 委托书已删除！
                message.putMessage("SVCMessage", "177");
                map.put("err", message);
                return map;
            }
        } else {
            // 委托书不存在！
            message.putMessage("SVCMessage", "178");
            map.put("err", message);
            return map;
        }
        return map;
    }

    // 删除服务包
    @Override
    public SvcServiceRequestViewDTO DeleteServicPack(
            String vServicePack, SvcServiceRequestViewDTO SVCServiceRequestVO) {

        // 获取建议项目
        DbUnionCommonDto view = new DbUnionCommonDto();
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        view.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
        view.setQueryConditions("a.VServicePack", 0, vServicePack);
        List<SVCServiceRequestItemVODTO> returnlist =
                svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfor.getnDID(), view, vCusGroupId);
        if (returnlist != null && returnlist.size() > 0) {
            for (int i = 0; i < returnlist.size(); i++) {
                SvcOrderItemPO itemPO = new SvcOrderItemPO();
                QueryWrapper<SvcOrderItemPO> queryitemPO = new QueryWrapper<>();
                queryitemPO.eq("ID", returnlist.get(i).getiD());
                List<SvcOrderItemPO> listorderitem = itemPO.selectList(queryitemPO);
                if (listorderitem != null && listorderitem.size() > 0) {
                    // 删除时留下记录 原触发器功能
                    SvcOrderItemDelPO delPO = new SvcOrderItemDelPO();
                    BeanUtils.copyProperties(listorderitem.get(0), delPO);
                    delPO.insertOrUpdate();
                }

                itemPO.deleteById(returnlist.get(i).getiD());
            }
        }

        // 预估备件
        DbUnionCommonDto preSPAView = new DbUnionCommonDto();

        preSPAView.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
        preSPAView.setQueryConditions("a.VServicePack", 0, vServicePack);
        List<SVCServiceRequestSpaDTO> viewSpa =
                svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(preSPAView);
        if (viewSpa != null && viewSpa.size() > 0) {
            for (int i = 0; i < viewSpa.size(); i++) {
                SvcOrderSpaPO SvcOrderSpaPO = new SvcOrderSpaPO();
                SvcOrderSpaPO.deleteById(viewSpa.get(i).getiD());
            }
        }
        DbUnionCommonDto viewChk = new DbUnionCommonDto();
        viewChk.setQueryConditions("a.NMainID", 0, SVCServiceRequestVO.getiD());
        viewChk.setQueryConditions("ifnull(a.VServicePack,'')", 1, "''");
        List<SVCServiceRequestItemVODTO> chkList =
                svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfor.getnDID(), viewChk, vCusGroupId);
        if (chkList == null || (chkList != null && chkList.size() == 0)) {
            SvcOrderPO querypo = new SvcOrderPO();
            querypo = querypo.selectById(SVCServiceRequestVO.getiD());
            SvcOrderPO updatepo = new SvcOrderPO();
            BeanUtils.copyProperties(querypo, updatepo);
            updatepo.setUpdateOn(SVCServiceRequestVO.getUpdateOn());
            updatepo.setcServicePack(0);
            updatepo.updateById();
            SVCServiceRequestVO.setiD(updatepo.getiD());
            SVCServiceRequestVO.setUpdateOn(updatepo.getUpdateOn());
            SVCServiceRequestVO.setcServicePack(updatepo.getcServicePack());
        }

        return SVCServiceRequestVO;
    }

    /// <summary>
    /// 校验维修项目存在性
    /// </summary>
    /// <param name="EntityName"></param>
    /// <param name="ID"></param>
    /// <param name="CodeName"></param>
    /// <param name="CodeValue"></param>
    /// <returns></returns>
    public Boolean SelfIsExist(String EntityName, String ID, String CodeName, String CodeValue) {
        /**
         * 这块调用的时候 会有风险，不想做映射，入参强制写入实体对象名称 下面用if 或者 case 判断，如果未找到实体 直接返回false 调用的时候需要看看你传入的实体名称中有没有if 分支
         */
        Boolean ret_bool = false;

        if ("SVCServiceRequestToolVO".equals(EntityName)) {
            DbUnionCommonDto view = new DbUnionCommonDto();
            DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
            view.setQueryConditions("a.NMainID", 0, ID);
            view.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            view.setQueryConditions("a." + CodeName, 0, CodeValue);
            List<SVCServiceRequestToolVO> SPT0103SVCServiceRequestToolList =
                    svc0101Mapper.SVCServiceRequestToolVO(view);
            if (SPT0103SVCServiceRequestToolList != null && SPT0103SVCServiceRequestToolList.size() > 0) {
                ret_bool = true;
            } else {
                ret_bool = false;
            }
        } else if ("SVCServiceRequestItemVO".equals(EntityName)) {
            DbUnionCommonDto view = new DbUnionCommonDto();
            DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
            view.setQueryConditions("a.NMainID", 0, ID);
            view.setQueryConditions("a." + CodeName, 0, CodeValue);
            List<SVCServiceRequestItemVODTO> temList =
                    svc0104SvcOrderMapper.sVCServiceRequestItemVO(userInfor.getnDID(), view, vCusGroupId);
            if (temList != null && temList.size() > 0) {
                ret_bool = true;
            } else {
                ret_bool = false;
            }
        } else if ("SVCServiceRequestSpaVO".equals(EntityName)) {
            DbUnionCommonDto view = new DbUnionCommonDto();
            DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
            view.setQueryConditions("a.NMainID", 0, ID);
            view.setQueryConditions("a.vspa", 0, CodeValue.split("@")[0]);
            view.setQueryConditions("a.vmodule", 0, CodeValue.split("@")[1]);
            view.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            List<SVCServiceRequestSpaDTO> temList =
                    svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(view);
            if (temList != null && temList.size() > 0) {
                ret_bool = true;
            } else {
                ret_bool = false;
            }
        } else if ("SVCServiceRequestSugeestMitVO".equals(EntityName)) {
            DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
            DbUnionCommonDto getxm = new DbUnionCommonDto();
            getxm.setQueryConditions("a.nMainid", 0, ID);
            getxm.setQueryConditions("a." + CodeName, 0, CodeValue);
            getxm.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            List<SVCServiceRequestSugeestMitVO> sugItemlist =
                    sVCGetSVCSugeestMitPRMapper.sVCGetSVCSugeestMitPRList(getxm);
            if (sugItemlist != null && sugItemlist.size() > 0) {
                ret_bool = true;
            } else {
                ret_bool = false;
            }
        }

        return ret_bool;
    }

    /// <summary>
    /// 校验复制委托书类别
    /// </summary>
    /// <param name="userInfor"></param>
    /// <param name="id"></param>
    /// <param name="vSvcKind"></param>
    /// <param name="vMessageCode"></param>
    /// <param name="vBillNO"></param>
    /// <returns></returns>
    private Map<String, Object> CheckCopySvcKind(
            DMSLoginInfoDto userInfor,
            String id,
            String vSvcKind,
            SvcServiceRequestViewDTO SVCServiceRequestVO) {
        Map<String, Object> map = new HashMap<>();
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.iD", 0, id);
        SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        String vMessageCode = "";
        SvcServiceRequestViewDTO dto = new SvcServiceRequestViewDTO();

        if (list != null && list.size() > 0) {
            CustomerPO customerPO = new CustomerPO();
            QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("vCus", list.get(0).getvCus());
            queryWrapper.eq("ndid", userInfor.getnDID());
            List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
            if (cuslistPO != null && cuslistPO.size() > 0) {
                customerPO = cuslistPO.get(0);
                List<STMCityVODTO> vCityLinklist = new ArrayList<>();
                vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
                list.get(0).setvCityLink(vCityLinklist);
                list.get(0).setvCusAddrDetail(customerPO.getvCusAddrDetail());
            }

            if (vSvcKind.equals(list.get(0).getvSvcKind())) {
                vMessageCode = "046";
                map.put("err", vMessageCode);
                return map;
            }
            dto = list.get(0);
            map.put("sVCServiceRequestVO", dto);
        } else {
            return map;
        }
        return map;
    }

    /// <summary>
    /// 校验重复委托书号
    /// </summary>
    /// <param name="userInfor"></param>
    /// <param name="vBillNO"></param>
    /// <param name="vMessageCode"></param>
    /// <returns></returns>
    private String CheckCopyBillNO(DMSLoginInfoDto userInfor, String vBillNO) {
        DbUnionCommonDto SVCVO = new DbUnionCommonDto();
        SVCVO.setQueryConditions("a.VBillNO", 0, vBillNO);
        SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
        List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);
        String vMessageCode = "";

        if (list != null && list.size() > 0) {
            vMessageCode = "006";
            return vMessageCode;
        }
        return vMessageCode;
    }

    @Override
    public Map<String, Object> viewSugItem(SVCServiceRequestVO SVCServiceRequestVO) {
        //		ISDO SVCServiceRequestVO = In.GetSDO("SVCServiceRequestVO");
        Map<String, Object> map = new HashMap<String, Object>();
        // 获取建议项目
        List<SVCServiceRequestSugeestMitVO> sugItemList =
                svc0101_04Service.SelfGetSugItemByMainID(
                        SVCServiceRequestVO.getiD(), SVCServiceRequestVO.getvVin(), 1);
        map.put("sVCServiceRequestSugeestMitVO", sugItemList);
        map.put("sVCServiceRequestVO", SVCServiceRequestVO);
        return map;
    }

    // 批量增加维修项目
    @Override
    public Map<String, Object> batchadditem_pdi(BatchAddItemPDIVO batchAddItemPDIVO) {
        List<SvcServiceRequestViewDTO> svcServiceRequestViewDTOList =
                batchAddItemPDIVO.getListSvcServiceRequest();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < svcServiceRequestViewDTOList.size(); i++) {
            String svcID = svcServiceRequestViewDTOList.get(i).getiD();

            //  项目
            List<SVCBatchSelectItemCM> itemTable = batchAddItemPDIVO.getItemTable();
            // 备件
            List<SVCBatchSelectItemSPACM> spaTable = batchAddItemPDIVO.getSpaTable();
            // 套餐维修项目表
            List<SVCBatchSelectSuitItemCM> suitItemTable = batchAddItemPDIVO.getSuitItemTable();
            // 工具
            List<SVCBatchSelectItemSPTCM> sptTable = batchAddItemPDIVO.getSptTable();

            BatchAddItemVO itemVO = new BatchAddItemVO();
            itemVO.setsVCServiceRequestVO_iD(svcID);
            itemVO.setItemTable(itemTable);
            itemVO.setSpaTable(spaTable);
            itemVO.setSuitItemTable(suitItemTable);
            itemVO.setSptTable(sptTable);
            map = batchadditem(itemVO);
        }
        return map;
    }

    /**
     * 校验是否新能源车及新能源级别\
     *
     * @param vvin String
     * @return X:非新能源车；N：没有查到车型权限；0、1、2、3：查询到的维修级别
     */
    @Override
    public String checkNevLevel(String vvin) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);

        if (vvin == null || "".equals(vvin) || vvin.length() < 17) {
            return "X";
        }

        VehiclePO vehiclePO = new VehiclePO();
        QueryWrapper<VehiclePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ndid", userInfor.getnDID());
        queryWrapper.eq("vvin", vvin);
        List<VehiclePO> vehiclePOList = vehiclePO.selectList(queryWrapper);
        if (vehiclePOList.isEmpty()) {
            return "X";
        }

        MdaProductMixPO mdaProductMixPO = new MdaProductMixPO();
        QueryWrapper<MdaProductMixPO> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", vehiclePOList.get(0).getnSaleTypeID());
        List<MdaProductMixPO> mdaProductMixPOList = mdaProductMixPO.selectList(queryWrapper2);
        if (mdaProductMixPOList.isEmpty()) {
            return "X";
        } else if ("0".equals(mdaProductMixPOList.get(0).getNevFlag())
                || StringUtils.isNullOrEmpty(mdaProductMixPOList.get(0).getNevFlag())) {
            return "X";
        }

        if (userInfor.getcMainBranch() == null || "1".equals(userInfor.getcMainBranch())) {
            MdaProductMixPO mdaProductMixPO2 = new MdaProductMixPO();
            QueryWrapper<MdaProductMixPO> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("id", mdaProductMixPOList.get(0).getnParentID());
            List<MdaProductMixPO> mdaProductMixPOList2 = mdaProductMixPO2.selectList(queryWrapper3);

            if (!mdaProductMixPOList2.isEmpty()) {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String format1 = dateTimeFormatter.format(LocalDateTime.now());
                String format2 = dateTimeFormatter.format(LocalDateTime.now());

                SvcRepairLevelPO svcRepairLevelPO = new SvcRepairLevelPO();
                QueryWrapper<SvcRepairLevelPO> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("ndid", userInfor.getnDID());
                queryWrapper4.eq("xh", mdaProductMixPOList2.get(0).getvProdMix());
                queryWrapper4.le("guebg", format1);
                queryWrapper4.ge("GUEEN", format2);
                queryWrapper4.orderByDesc("Createon");
                List<SvcRepairLevelPO> svcRepairLevelPOList = svcRepairLevelPO.selectList(queryWrapper4);
                if (!svcRepairLevelPOList.isEmpty()) {
                    return svcRepairLevelPOList.get(0).getQxjb();
                } else {
                    return "N";
                }

            } else {
                return "N";
            }
        } else {
            return "1";
        }
    }

    @Override
    public Map<String, Object> getSvcRequestStateFromCusAPP(SVCServiceRequestVO para) {
        Map<String, Object> data =
                svcToCusAppService.getSvcStateFromCusAPP(para.getvBillNO(), "Request");
        return data;
    }

    @Override
    public Message sendTOCusAPP(SVCServiceRequestVO para) {
        Message message = svcToCusAppService.sendSvcRequestTOCusAPP(para.getiD());
        return message;
    }

    /**
     * @desc 取当前项目默认工时优惠率
     * @author zCMeow
     * @date 2020-07-17 14:39:00
     */
    private BigDecimal getCurrentDefultCutRate(
            SVCServiceRequestItemVO itemVO, SvcServiceRequestViewDTO svcServiceRequestVO) {

        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        // 是否免费
        Boolean isFree = false;

        // 循环校验listItem中工时优惠率为0时取预约和客户级别优惠率
        if (itemVO != null) {
            if (itemVO.getnManhaurDisRate() == null
                    || itemVO.getnManhaurDisRate().compareTo(new BigDecimal(0)) == 0) {
                // 获取预约工时优惠率和客户级别工时优惠率-ybs
                BigDecimal preManhaurDisRate = new BigDecimal(0); // 声明预约工时优惠率
                BigDecimal cusManhaurDisRate = new BigDecimal(0); // 声明客户级别工时优惠率
                // 有预约isBook=1
                String isBook1 = svcServiceRequestViewMapper.isBook(svcServiceRequestVO.getiD());
                if ("1".equals(isBook1)) {
                    RateInfoDTO preManhaurRate =
                            svcServiceRequestViewMapper.getBookManhaurRate(userInfor.getnDID());
                    if (preManhaurRate != null) {
                        preManhaurDisRate = new BigDecimal(preManhaurRate.getBookManhaurRate());
                    }
                }
                RateInfoDTO cusManhaurRate =
                        svcServiceRequestViewMapper.getGradeManhaurRate(svcServiceRequestVO.getiD());
                if (cusManhaurRate != null) {
                    cusManhaurDisRate = new BigDecimal(cusManhaurRate.getGradeManhaurRate());
                }
                if (preManhaurDisRate.compareTo(cusManhaurDisRate) > 0) {
                    itemVO.setnManhaurDisRate(preManhaurDisRate);
                } else {
                    itemVO.setnManhaurDisRate(cusManhaurDisRate);
                }
            }
        }
        BigDecimal manhourDisRate = BigDecimal.ZERO;
        if (itemVO != null && !StringUtils.isNullOrEmpty(itemVO.getnManhaurDisRate().toString())) {
            manhourDisRate = itemVO.getnManhaurDisRate();
        }
        /**
         * @desc 此处做已获取完的最大优惠率和分时段优惠作比较，如果分时段优惠力度大则取分时段优惠并修改对象中的工时优惠率
         * @author yubingsen
         * @date 2020-10-10
         */
        String maxDaypartingRate = "";
        if (itemVO != null && !StringUtils.isNullOrEmpty(itemVO.getvItem())) {
            maxDaypartingRate = getMaxDaypartingDisCountRate(itemVO.getvItem());

            logger.info("获取到的最大分时段优惠:{}", maxDaypartingRate);
            if (!StringUtils.isNullOrEmpty(maxDaypartingRate)) {
                if (manhourDisRate.compareTo(new BigDecimal(maxDaypartingRate)) < 0) {
                    manhourDisRate = new BigDecimal(maxDaypartingRate);
                    itemVO.setnManhaurDisRate(manhourDisRate);
                }
            }
        }

        return manhourDisRate;
    }

    @Override
    public Page<SVCGetServiceRequest> searchType(
            SVCServiceRequestQueryParaVO sVCServiceRequestQueryParaVO) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        Page<SVCGetServiceRequest> page =
                new Page<SVCGetServiceRequest>(
                        sVCServiceRequestQueryParaVO.getCurrentPage(),
                        sVCServiceRequestQueryParaVO.getPageSize());
        String typeTag = sVCServiceRequestQueryParaVO.getTypeTag();
        //        List<SVCSvcKindSHVODTO> SVCSvcKindSHVODTO= sVCKindSH0101();
        DbUnionCommonDto dbUnion = new DbUnionCommonDto();
        dbUnion.setQueryConditions("t.nDID", 0, userInfor.getnDID());
        dbUnion.setQueryConditions("t.nbid", 0, userInfor.getnBID());
        //        //分别是保养和维修的
        //        List<String> bList=new ArrayList<>();
        //        List<String> wList=new ArrayList<>();
        //        for(SVCSvcKindSHVODTO sVCSvcKindSHVODTO:SVCSvcKindSHVODTO){
        //            if("0-2".indexOf(sVCSvcKindSHVODTO.getvSvcCls())!=-1){
        //                bList.add(sVCSvcKindSHVODTO.getvSvcCls());
        //            }else{
        //                wList.add(sVCSvcKindSHVODTO.getvSvcCls());
        //            }
        //        }

        List<SVCGetServiceRequest> searchType = new ArrayList<>();
        if ("bType".equals(typeTag)) {
            // 保养仅显示 0- 2-
            dbUnion.setQueryConditions("t.vsvckind", DBType.DB_TYPE_IN, "0,2");
            dbUnion.setQueryConditions("t.vRepairStatus", 1, "02");
            dbUnion.setQueryConditions("t.nSVCAdviserID", 0, userInfor.getiD());
            searchType = svc0101Mapper.searchType(dbUnion, page);
        } else if ("wType".equals(typeTag)) {
            // 维修显示非 0- 2-
            dbUnion.setQueryConditions("t.vsvckind", DBType.DB_TYPE_NOT_IN, "0,2");
            dbUnion.setQueryConditions("t.vRepairStatus", 1, "02");
            dbUnion.setQueryConditions("t.nSVCAdviserID", 0, userInfor.getiD());
            searchType = svc0101Mapper.searchType(dbUnion, page);
        } else if ("jType".equals(typeTag)) {
            dbUnion.setQueryConditions("t.VSVCAdviser", 0, userInfor.getvPerson());
            searchType = svc0101Mapper.searchRegister(dbUnion, page);
        }
        // 已经结账的不显示了
        page.setRecords(searchType);
        return page;
    }


    @Override
    public List<Map<String, Object>> hxQuery(Map<String, String> para) {
        // 取得入参
        String vVin = para.get("vVin");
        String redeemcode = para.get("redeemcode");
        Map js_praa = new HashMap();
        if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(vVin)) {
            js_praa.put("vin", vVin);
        }
        if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(redeemcode)) {
            js_praa.put("redeemcode", redeemcode);
        }
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        String cardTicketKey =
                stmCommonService.GetParameters("cardTicketKey", userInfor.getnBID(), "SVC");
        // 经销商代码
        String CFWZDM = pucCommonService.getDealerCode(userInfor.getnDID());
        js_praa.put("cardTicketKey", cardTicketKey);
        js_praa.put("dealercode", CFWZDM);
        js_praa.put("currentPage", "1");
        js_praa.put("pageSize", "200");
        logger.info("接车制单卡券查询 接口入参" + js_praa.toString());
        Map<String, Object> json_returncarinfo = svcToCdpService.queryTicketListServer(js_praa);
        logger.info("接车制单卡券查询 接口返回" + json_returncarinfo.toString());
        String returnStatus = json_returncarinfo.get("returnStatusCode").toString();
        List<Map<String, Object>> outSDOS = new ArrayList<>();
        if ("200".equals(returnStatus) || "CDP.TICKET.200".equals(returnStatus)) {
            List<Map<String, Object>> json_data =
                    (List<Map<String, Object>>) json_returncarinfo.get("data");

            for (int i = 0; i < json_data.size(); i++) {
                Map<String, Object> SVCqueryTicketListServerCM = new HashMap<>();
                SVCqueryTicketListServerCM.put("cardTicketName", json_data.get(i).get("cardTicketName"));
                SVCqueryTicketListServerCM.put("cardTicketType", json_data.get(i).get("cardTicketType"));
                SVCqueryTicketListServerCM.put("businessCode", json_data.get(i).get("businessCode"));
                SVCqueryTicketListServerCM.put("starttime", json_data.get(i).get("starttime"));
                SVCqueryTicketListServerCM.put("endtime", json_data.get(i).get("endtime"));
                //                SVCqueryTicketListServerCM.put("accountTime",
                // json_data.get(i).get("accountTime").toString().equals("") ? "1900-01-01 00:00:00" :
                // json_data.get(i).get("accountTime").toString());
                SVCqueryTicketListServerCM.put(
                        "supportAmount",
                        json_data.get(i).get("supportAmount") == null
                                || "".equals(json_data.get(i).get("supportAmount").toString())
                                ? "0"
                                : json_data.get(i).get("supportAmount").toString());
                SVCqueryTicketListServerCM.put(
                        "valueTxt",
                        json_data.get(i).get("valueTxt") == null
                                || "".equals(json_data.get(i).get("valueTxt").toString())
                                ? "0"
                                : json_data.get(i).get("valueTxt").toString());
                SVCqueryTicketListServerCM.put("aid", json_data.get(i).get("aid"));
                SVCqueryTicketListServerCM.put(
                        "cardTicketStatus", json_data.get(i).get("cardTicketStatus"));
                SVCqueryTicketListServerCM.put(
                        "cardTicketChildStatus", json_data.get(i).get("cardTicketChildStatus"));
                SVCqueryTicketListServerCM.put("name", json_data.get(i).get("name"));
                SVCqueryTicketListServerCM.put("idCard", json_data.get(i).get("idCard"));
                SVCqueryTicketListServerCM.put("phone", json_data.get(i).get("phone"));
                SVCqueryTicketListServerCM.put("vin", json_data.get(i).get("vin"));
                SVCqueryTicketListServerCM.put(
                        "usableAmount",
                        json_data.get(i).get("usableAmount") == null
                                || "".equals(json_data.get(i).get("usableAmount").toString())
                                ? "0"
                                : json_data.get(i).get("usableAmount").toString());
                SVCqueryTicketListServerCM.put(
                        "alreadyAmount",
                        json_data.get(i).get("alreadyAmount") == null
                                || "".equals(json_data.get(i).get("alreadyAmount").toString())
                                ? "0"
                                : json_data.get(i).get("alreadyAmount").toString());
                SVCqueryTicketListServerCM.put(
                        "usableNum",
                        json_data.get(i).get("usableNum") == null
                                || "".equals(json_data.get(i).get("usableNum").toString())
                                ? "0"
                                : json_data.get(i).get("usableNum").toString());

                outSDOS.add(SVCqueryTicketListServerCM);
            }
        } else {
            String returnMessage = json_returncarinfo.get("returnMessage").toString();
            message.putMessage("SVCMessage", "125", new String[]{returnMessage});
        }
        return outSDOS;
    }

    /**
     * 分别查询客档车档是否存在，都存在返回1否则0
     *
     * @param svcArchivesDTO
     * @return
     */
    @Override
    public Integer archivesExist(SvcArchivesDTO svcArchivesDTO) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        Integer i = null;
        String vVin = svcArchivesDTO.getvVin();
        String vLicenseTag = svcArchivesDTO.getvLicenseTag();
        String vArtificalId = svcArchivesDTO.getvArtificalId();

        if (com.vw.mep.dms.function.StringUtils.isNullOrEmpty(vVin) && com.vw.mep.dms.function.StringUtils.isNullOrEmpty(vLicenseTag)) {
            return 0;
        }

        //车档
        DbUnionCommonDto query = new DbUnionCommonDto();
        query.setQueryConditions("a.NDID", 0, userInfor.getnDID());
        if (!com.vw.mep.dms.function.StringUtils.isNullOrEmpty(vVin)) {
            query.setQueryConditions("a.VVin", 0, vVin);
        }
        if (!com.vw.mep.dms.function.StringUtils.isNullOrEmpty(vVin)) {
            query.setQueryConditions("a.vLicenseTag", 0, vLicenseTag);
        }
        List<CRMVehicleQueryVoDTO> vinList = cRMVehicleQueryVOMapper.cRMVehicleQueryVO(query);

        //客档
        CustomerInfoVO vCusVO = new CustomerInfoVO();
        vCusVO.setvCus(vArtificalId);
        Map<String, String> customer = (Map<String, String>) archivesFeignClient.getCustomer(userInfor.getnDID(), vCusVO).getData();

        if (vinList.size() > 0 && !customer.isEmpty() && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(customer.get("iD"))) {
            i = 1;
        } else {
            i = 0;
        }
        return i;
    }

    /**
     * 获取最大分时段优惠率
     *
     * @param vItemCode
     * @return
     * @author yubingsen
     * @date 2020-10-10
     */
    private String getMaxDaypartingDisCountRate(String vItemCode) {

        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        LocalDateTime now = LocalDateTime.now();
        String nManhaurDisRate = new String();
        String nMaterialDisRate = new String();
        // 1.查询当前项目是否有分时段优惠
        DbUnionCommonDto searchCondition = new DbUnionCommonDto();
        searchCondition.setQueryConditions("d.vItem", 0, vItemCode);
        searchCondition.setQueryConditions("d.nDID", 0, userInfo.getnDID());
        List<Map> rateList = svcGetDisCountByItemCodeMapper.getDaypartingDisCount(searchCondition);

        Map timeDisCount = new HashMap(); // 时间分时段优惠
        Map dateDisCount = new HashMap(); // 日期分时段优惠
        // 如果rateList为空当前项目没对应分时段优惠，则查询该项目有没有工时定额优惠
        if (!rateList.isEmpty()) {
            for (Map map : rateList) {
                if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(map.get("cDaily")) && Integer.valueOf(map.get("cDaily").toString()) == 1) {
                    timeDisCount = map;
                } else {
                    if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(map.get("dEnd"))) {
                        LocalDateTime dEnd = LocalDateTimeUtils.stringToLocalDateTime(map.get("dEnd").toString());
                        if (now.compareTo(dEnd) < 0) {
                            dateDisCount = map;
                        }
                    }
                }
            }
        } else {
            // 查询当前工时定额优惠
            DbUnionCommonDto stdConditions = new DbUnionCommonDto();
            stdConditions.setQueryConditions("d.vItem", 0, vItemCode);
            stdConditions.setQueryConditions("d.nDID", 0, userInfo.getnDID());
            List<Map> stdList = svcGetDisCountByItemCodeMapper.getStdDaypartingDisCount(searchCondition);
            if (!stdList.isEmpty()) {
                for (Map map : stdList) {
                    if (!StringUtils.isNullOrEmpty(map.get("cDaily").toString()) && Integer.valueOf(map.get("cDaily").toString()) == 1) {
                        timeDisCount = map;
                    } else {
                        if (!StringUtils.isNullOrEmpty(map.get("dEnd").toString())) {
                            LocalDateTime dEnd = LocalDateTimeUtils.stringToLocalDateTime(map.get("dEnd").toString());
                            if (now.compareTo(dEnd) < 0) {
                                dateDisCount = map;
                            }
                        }
                    }
                }
            }
        }
        // 取当前项目最大工时、材料优惠率
        if (timeDisCount.size() > 0 && dateDisCount.size() > 0) {
            String timeHourRate = new String(); // 时间工时优惠率
            String timeSpaRate = new String(); // 时间材料优惠率
            String dateHourRate = new String(); // 日期工时优惠率
            String dateSpaRate = new String(); // 日期材料优惠率
            // 判断当前日期是不是在日期优惠时段内 在则取出工时材料优惠率dateHourRate、dateSpaRate
            LocalDateTime dDateBegin = LocalDateTimeUtils.stringToLocalDateTime(dateDisCount.get("dBegin").toString());
            LocalDateTime dDateEnd = LocalDateTimeUtils.stringToLocalDateTime(dateDisCount.get("dEnd").toString());
            if (now.compareTo(dDateBegin) >= 0 && now.compareTo(dDateEnd) < 0) {
                dateHourRate = dateDisCount.get("nManhaurDisRate").toString();
                dateSpaRate = dateDisCount.get("nMaterialDisRate").toString();
            }
            // 判断当前时间是不是在时间优惠时段内 在则取出工时材料优惠率timeHourRate、timeSpaRate
            if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(timeDisCount.get("nManhaurDisRate"))) {
                LocalDateTime tDateBegin = LocalDateTimeUtils.stringToLocalDateTime(timeDisCount.get("dBegin").toString());
                LocalDateTime tDateEnd = LocalDateTimeUtils.stringToLocalDateTime(timeDisCount.get("dEnd").toString());
                String tTimeBegin = tDateBegin.getHour() + ":" + tDateBegin.getMinute() + ":" + tDateBegin.getSecond();
                String tTimeEnd = tDateEnd.getHour() + ":" + tDateEnd.getMinute() + ":" + tDateEnd.getSecond();
                String tTimeNow = now.getHour() + ":" + now.getMinute() + ":" + now.getSecond();
                Boolean less = compareTime(tTimeNow, tTimeBegin); // true为大于起始时间
                Boolean greatter = compareTime(tTimeNow, tTimeEnd); // false为小于结束时间
                if (less && !greatter) {
                    timeHourRate = timeDisCount.get("nManhaurDisRate").toString();
                    timeSpaRate = timeDisCount.get("nMaterialDisRate").toString();
                }
            }
            // 如果当前项目同时存在日期和时间分段优惠率，则取最大值
            if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(dateHourRate) && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(timeHourRate)) {
                if ((new BigDecimal(dateHourRate)).compareTo(new BigDecimal(timeHourRate)) >= 0) {
                    nManhaurDisRate = dateHourRate;
                    return nManhaurDisRate;
                } else {
                    nManhaurDisRate = timeHourRate;
                    return nManhaurDisRate;
                }
            } else if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(dateHourRate) && com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(timeHourRate)) {
                nManhaurDisRate = dateHourRate;
                return nManhaurDisRate;
            } else if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(timeHourRate) && com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(dateHourRate)) {
                nManhaurDisRate = timeHourRate;
                return nManhaurDisRate;
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 比较时间，当前时间大返回true，当前时间小返回false，其他返回null
     *
     * @param nowTime
     * @param otherTime
     * @return
     * @author yubingsen
     * @date 2020-10-10
     */
    private Boolean compareTime(String nowTime, String otherTime) {

        if (nowTime.indexOf(":") < 0 || otherTime.indexOf(":") < 0) {
            System.out.println("格式不正确");
        } else {
            String[] array1 = nowTime.split(":");
            int total1 = Integer.valueOf(array1[0]) * 3600 + Integer.valueOf(array1[1]) * 60 + Integer.valueOf(array1[2]);
            String[] array2 = otherTime.split(":");
            int total2 = Integer.valueOf(array2[0]) * 3600 + Integer.valueOf(array2[1]) * 60 + Integer.valueOf(array2[2]);
            return total1 - total2 > 0 ? true : false;

        }
        return null;
    }

    @Autowired
    FaiFeignClient faiFeignClient;

    @Override
    public RestResultResponse insetFaiServerRecom(Map<String, String> para) {
        JSONObject ServerVO = new JSONObject();
        JSONObject FaiServerRecomDTO = new JSONObject();
        FaiServerRecomDTO.put("vVin", para.get("vVin"));
        FaiServerRecomDTO.put("vCus", para.get("vCus"));
        FaiServerRecomDTO.put("uCusID", para.get("uCusID"));
        //获取用户信息
        DMSLoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        FaiServerRecomDTO.put("nDID", loginInfoDto.getnDID());
        FaiServerRecomDTO.put("dRecomPerson", loginInfoDto.getvPersonName());
        FaiServerRecomDTO.put("dRecomDate", LocalDateTime.now());
        ServerVO.put("FaiServerRecomDTO", FaiServerRecomDTO);
        return faiFeignClient.insetFaiServerRecom(loginInfoDto.getnDID(), ServerVO);
    }

    @Override
    public String pushPassengerFlow(Map<String, String> para) {
        //获取用户信息
        DMSLoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        para.put("nbid", loginInfoDto.getnBID());
        para.put("ndid", loginInfoDto.getnDID());
        Object result = retailFeignClient.pushPassengerFlow(loginInfoDto.getnDID(), para);
        return null;
    }

    @Override
    public Map<String, Object> doAddSpa(SVCServiceRequestVO para) {

        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        SPAListDefineCMDTO sdo = new SPAListDefineCMDTO();
        sdo.setP_Type("SVCRequest");
        sdo.setP_PriceTypeID("00000000-0000-0000-0000-000000000000");
        sdo.setP_OfferMode("");
        sdo.setP_PageIndex("1");
        sdo.setP_Module("SPA");
        sdo.setP_DID(userInfo.getnDID());
        sdo.setP_SuitID("00000000-0000-0000-0000-000000000000");
        sdo.setP_NBID(para.getnBID());
        sdo.setP_CQueryOnly(1);
        String vFilter = "";
        if (para.getvSvcKind().equals("0")
                || para.getvSvcKind().equals("1")
                || para.getvSvcKind().equals("S")
                || para.getvSvcKind().equals("V")
                || para.getvSvcKind().equals("Z")) {
            vFilter = "1";
        } else {
            vFilter = "0";
        }
        sdo.setP_Filter(para.getnSaleTypeID() == null ? "" : para.getnSaleTypeID() + ";" + vFilter);
        sdo.setnDefaultQty(BigDecimal.ONE);

        Map map = new HashMap();
        map.put("sPAListDefineCM", sdo);
        return map;

    }


    @Override
    public PadHomeCensus homeCensus() {
        PadHomeCensus padHomeCensus = new PadHomeCensus();
        /**
         * 待进场
         */
        Long stayInStation = 0L;
        /**
         * 待制单
         */
        Long pendingOrders = 0L;
        /**
         * 待完工
         */
        Long toBeCompleted = 0L;
        /**
         * 待交车
         */
        Long handOverCar = 0L;
        /**
         * 待结算
         */
        Long pendingSettlement = 0L;
        /**
         * 15分钟应交车
         */
        Long minutes15OverCar = 0L;
        /**
         * 正常
         */
        Long normalCount = 0L;
        /**
         * 超时
         */
        Long timeoutCount = 0L;


        List<SVCPadProgressDTO> list = pad0101Service.padprogressBar();

        for (SVCPadProgressDTO svcPadProgressDTO : list) {
            //待进场
            if ("DJZ".equals(svcPadProgressDTO.getStatus())) {
                stayInStation++;
                //待制单
            } else if ("DZD".equals(svcPadProgressDTO.getStatus())) {
                pendingOrders++;
                //待完工
            } else if ("DWG".equals(svcPadProgressDTO.getStatus())) {
                toBeCompleted++;
                //待交车
            } else if ("DJC".equals(svcPadProgressDTO.getStatus())) {
                handOverCar++;
                //待结算
            } else if ("DJS".equals(svcPadProgressDTO.getStatus())) {
                pendingSettlement++;
            }

            if ("0".equals(svcPadProgressDTO.getOvertime())) {
                normalCount++;
            } else if ("1".equals(svcPadProgressDTO.getOvertime())) {
                timeoutCount++;
            }

            if (svcPadProgressDTO.getdPromiseFinish() != null) {
                Duration duration = Duration.between(svcPadProgressDTO.getdPromiseFinish(), LocalDateTime.now());
                long durationMinute = duration.toMinutes();
                if (durationMinute > 0 && durationMinute <= 15) {
                    minutes15OverCar++;
                }
            }

        }

        padHomeCensus.setStayInStation(stayInStation);
        padHomeCensus.setPendingOrders(pendingOrders);
        padHomeCensus.setToBeCompleted(toBeCompleted);
        padHomeCensus.setHandOverCar(handOverCar);
        padHomeCensus.setPendingSettlement(pendingSettlement);
        padHomeCensus.setMinutes15OverCar(minutes15OverCar);
        padHomeCensus.setNormalCount(normalCount);
        padHomeCensus.setTimeoutCount(timeoutCount);
        return padHomeCensus;
    }

    @Override
    public Map<String, Object> upLoadCRM(SaveSVCServiceRequestSpaVO saveSVCServiceRequestSpaVO) {
        SvcServiceRequestViewDTO sVCServiceRequestVO = saveSVCServiceRequestSpaVO.getsVCServiceRequestVO();
        if (("01").equals(sVCServiceRequestVO.getvOrderType())){
            //不是原厂车不创建服务订单
            MdaProductMixPO mixPO = new MdaProductMixPO();
            mixPO.setiD(sVCServiceRequestVO.getnSaleTypeID());
            mixPO = mixPO.selectById();
            if (mixPO != null && !StringUtils.isNullOrEmpty(mixPO.getiD())){
                if (null == (mixPO.getcFactory()) || (0) == (mixPO.getcFactory())) {
                    message.putMessage("SVCMessage", "125", new String[]{"非三一设备不允许使用原厂件，请确认"});
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        //获取所有预估备件
        DbUnionCommonDto db = new DbUnionCommonDto();
        db.setQueryConditions("a.nmainid",0,sVCServiceRequestVO.getiD());
        List<SVCServiceRequestSpaDTO> sVCServiceRequestSpaVO = this.svcServiceRequestSpaDTOMapper.sVCServiceRequestSpaVO(db);

        //判断是否有需要上传的数据
        if(sVCServiceRequestSpaVO.isEmpty()){
//            message.putMessage("SVCMessage", "125", new String[]{"不存在需要上传的配件信息"});
        }else{
            List<SVCServiceRequestSpaDTO> isNeedUploadSpa = new ArrayList<>();
            for (SVCServiceRequestSpaDTO item:sVCServiceRequestSpaVO
                 ) {
                //原厂件并且没有上传的
                if((("1").equals(item.getvChannel()) || ("01").equals(item.getvChannel()))){
                    //查已经上传的数量
                    SvcUploadCrmSpaPO svcUploadCrmSpaPO = new SvcUploadCrmSpaPO();
                    QueryWrapper<SvcUploadCrmSpaPO> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("nMainid",item.getnMainID());
                    queryWrapper.eq("vSpa",item.getvSpa());
                    queryWrapper.eq("ndid",item.getnDID());
                    svcUploadCrmSpaPO = svcUploadCrmSpaPO.selectOne(queryWrapper);
                    if (svcUploadCrmSpaPO == null || StringUtils.isNullOrEmpty(svcUploadCrmSpaPO.getiD())){
                        isNeedUploadSpa.add(item);
                    }else{
                        if (item.getnQty().compareTo(svcUploadCrmSpaPO.getnQty()) != 0){
//                            item.setnQty(item.getnQty().subtract(svcUploadCrmSpaPO.getnQty()));
                            isNeedUploadSpa.add(item);
                        }
                    }
//                    isNeedUploadSpa.add(item);
                }
            }
            if(isNeedUploadSpa.isEmpty()){
//                message.putMessage("SVCMessage", "125", new String[]{"不存在需要上传的配件信息"});
            }else{
                String vSpas = "";
                for (SVCServiceRequestSpaDTO item: isNeedUploadSpa) {
                    String vSpa = item.getvSpa();
                    SpaGetDrawDetailForSvcVODTO spaGetDrawDetailForSvcVODTO = this.svc0104SvcOrderMapper.getDrawDetailForOrderByVSpa(item.getnDID(),item.getnMainID(),vSpa);
                    if (spaGetDrawDetailForSvcVODTO != null && !com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(spaGetDrawDetailForSvcVODTO.getvSpa())){
                        if (null != spaGetDrawDetailForSvcVODTO.getnQty() && BigDecimal.ZERO.compareTo(spaGetDrawDetailForSvcVODTO.getnQty()) != 0){
                            vSpas = vSpas + "【" + vSpa + "】" + "、";
                        }
                    }
                }
                if (!StringUtils.isNullOrEmpty(vSpas)){
                    vSpas = vSpas.substring(0, vSpas.length() -1);
                    message.putMessage("SVCMessage", "125", new String[]{vSpas + "配件未完全退库，请在CRM退库后进行操作"});
                }else {
                    saveSVCServiceRequestSpaVO.setsVCServiceRequestSpaVO(isNeedUploadSpa);
                    saveSVCServiceRequestSpaVO.setVlkTel(sVCServiceRequestVO.getvLkTel());
                    saveSVCServiceRequestSpaVO.setVlkName(sVCServiceRequestVO.getvLkName());
                    saveSVCServiceRequestSpaVO.setVlkMobile(sVCServiceRequestVO.getvLkMobile());
                    this.svcToSanyCrmService.upLoadSpaToSanyCrm(saveSVCServiceRequestSpaVO);
                }
            }

            for (SVCServiceRequestSpaDTO item:isNeedUploadSpa
                 ) {
                SvcOrderSpaPO svcOrderSpaPO = new SvcOrderSpaPO();
                svcOrderSpaPO.setiD(item.getiD());
                svcOrderSpaPO = svcOrderSpaPO.selectById();
                svcOrderSpaPO.setcUpload("1");
                svcOrderSpaPO.setdUpload(LocalDateTime.now());
                svcOrderSpaPO.updateById();
                SvcUploadCrmSpaPO svcUploadCrmSpaPO = new SvcUploadCrmSpaPO();
                QueryWrapper<SvcUploadCrmSpaPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("nMainid",item.getnMainID());
                queryWrapper.eq("vSpa",item.getvSpa());
                queryWrapper.eq("ndid",item.getnDID());
                svcUploadCrmSpaPO = svcUploadCrmSpaPO.selectOne(queryWrapper);
                if (svcUploadCrmSpaPO == null || StringUtils.isNullOrEmpty(svcUploadCrmSpaPO.getiD())){
                    SvcUploadCrmSpaPO svcUploadCrmSpaPOAdd = new SvcUploadCrmSpaPO();
                    svcUploadCrmSpaPOAdd.setvSpa(item.getvSpa());
                    svcUploadCrmSpaPOAdd.setnMainID(item.getnMainID());
                    svcUploadCrmSpaPOAdd.setnQty(item.getnQty());
                    svcUploadCrmSpaPOAdd.setnDID(item.getnDID());
                    svcUploadCrmSpaPOAdd.insert();
                }else{
                    if (item.getnQty().compareTo(svcUploadCrmSpaPO.getnQty()) != 0){
                        svcUploadCrmSpaPO.setnQty(item.getnQty());
                        svcUploadCrmSpaPO.updateById();
                    }
                }
            }

            List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(sVCServiceRequestVO.getiD());
            map.put("sVCServiceRequestSpaVO", spaList);
        }
        // 获取预估备件

        return map;
    }

    @Override
    public List selectListForExcelExport(Object params, int page) {

        SVCServiceRequestQueryParaVO condition = (SVCServiceRequestQueryParaVO) params;
        condition.setCurrentPage(page);
        condition.setSearchCount(false);
        SVC0101FYVO result = search(condition);
        Page<SVCGetServiceRequest> resPage = result.getTableData();
        return resPage.getRecords();
    }

    @Override
    public Map<String, Integer> getAllTaskNum() {
        //获取用户信息
        DMSLoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        return svc0101Mapper.getAllTaskNum(loginInfoDto.getiD(), loginInfoDto.getnDID(), loginInfoDto.getvPerson());
    }


    // APP编辑方法
    @Override
    public Map<String, Object> appEdit(@RequestBody SVCGetServiceRequest sVCGetServiceRequest) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        userInfor.setnDID(sVCGetServiceRequest.getnBID());

        // FD 上传状态
        String DTSSstutes = "0";
        // 创建返回Map
        Map<String, Object> returnMap = new HashMap<>();
        // 初始化界面数据字典
        Map<String, Object> Dict = SetEnterDict(userInfor.getnDID());
        returnMap.put("dict", Dict);
        if (!StringUtils.isNullOrEmpty(sVCGetServiceRequest.getiD())) {
            DbUnionCommonDto SVCVO = new DbUnionCommonDto();
            SVCVO.setQueryConditions("a.ndid", 0, userInfor.getnDID());
            SVCVO.setQueryConditions("a.iD", 0, sVCGetServiceRequest.getiD());
            List<SvcServiceRequestViewDTO> list = svcServiceRequestViewMapper.query(SVCVO);


            // 获取到了委托书信息
            if (list.size() > 0) {
                // 增加预约标识
                if("0".equals(list.get(0).getvSvcFrom())){
                    returnMap.put("isBook", "1");
                }else if("1".equals(list.get(0).getvSvcFrom())){
                    SvcEstimatePO svcEstimatePO = new SvcEstimatePO();
                    svcEstimatePO.setiD(list.get(0).getnSvcFromBillID());
                    svcEstimatePO = svcEstimatePO.selectById();
                    if(!StringUtils.isNullOrEmpty(svcEstimatePO.getiD()) && ("1").equals(svcEstimatePO.getvSvcFrom())){
                        returnMap.put("isBook", "1");
                    }
                }
                // 获取车辆信息
                DbUnionCommonDto getVehicleInfoVO = new DbUnionCommonDto();
                getVehicleInfoVO.setQueryConditions("a.ndid", 0, list.get(0).getnDID());
                getVehicleInfoVO.setQueryConditions("a.vvin", 0, list.get(0).getvVin());
                List<CRMSALGetVehicleInfoVODTO> vehInfoList =
                        crm0001Mapper.sALGetVehicleInfoVO(getVehicleInfoVO);
                if (vehInfoList.size() > 0) {
                    list.get(0).setdProd(vehInfoList.get(0).getdProd());
                    list.get(0).setcOwnSell(vehInfoList.get(0).getcOwnSell());
                }
                // 查询客户档案填充省市区县 和客户详细地址
                // 增加省市区县list
                CustomerPO customerPO = new CustomerPO();
                QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("vCus", list.get(0).getvCus());
                queryWrapper.eq("ndid", userInfor.getnDID());
                List<CustomerPO> cuslistPO = customerPO.selectList(queryWrapper);
                if (cuslistPO != null && cuslistPO.size() > 0) {
                    customerPO = cuslistPO.get(0);
                    List<STMCityVODTO> vCityLinklist = new ArrayList<>();
                    vCityLinklist = svcToCrmService.citylinkList(vCityLinklist, customerPO);
                    list.get(0).setvCityLink(vCityLinklist);
                    list.get(0).setvCusAddrDetail(customerPO.getvCusAddrDetail());
                    list.get(0).setnCityID(customerPO.getnCityID());

                    CustomerPO customerPO1 = cuslistPO.get(0);
                    String vAddrStr = customerPO1.getvProvince() + "," + customerPO1.getvCity();
                    if (!com.vw.mep.dms.api.common.utils.StringUtils.isNullOrEmpty(customerPO1.getvArea())){
                        vAddrStr = vAddrStr + "," + customerPO1.getvArea();
                    }
                    list.get(0).setvAddrSre(vAddrStr);
                }
                // 查询委托书签字PDF
                UpfilePO upfilePO = new UpfilePO();
                QueryWrapper<UpfilePO> fileWapper = new QueryWrapper<>();
                fileWapper.eq("nCorBillID",list.get(0).getiD());
                fileWapper.eq("vUseCase","Svc0101");
                fileWapper.eq("vModule","PDF");
                fileWapper.orderByDesc("updateOn");
                List<UpfilePO> upfilePOList = upfilePO.selectList(fileWapper);
                upfilePO = upfilePOList.isEmpty() ? null : upfilePOList.get(0);
                Map orderMap = list.get(0).toMaps();
                orderMap.put("vUrl",upfilePO != null ? upfilePO.getvUrl() : "");
                returnMap.put("sVCServiceRequestVO", orderMap);
                // CRMInsuranceVO 保险
                List<CRMInsuranceVODTO> CRMInsuranceList =
                        getCRMInsuranceVO(list.get(0).getnDID(), list.get(0).getvVin());
                returnMap.put("cRMInsuranceVO", CRMInsuranceList);

                // 获取维修项目
                List<SVCServiceRequestItemVODTO> itemList = SelfGetItemByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestItemVO", itemList);

                // 获取预估备件
                List<SVCServiceRequestSpaDTO> spaList = SelfGetSPAByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestSpaVO", spaList);
                // 建议维修项目
                List<SVCServiceRequestSugeestMitVO> SelfGetSugItemByMainID =
                        svc0101_04Service.SelfGetSugItemByMainID(list.get(0).getiD(), "", 0);
                returnMap.put("sVCServiceRequestSugeestMitVO", SelfGetSugItemByMainID);

                // 获取专用工具
                List<SVCServiceRequestToolVO> toolList = SelfGetToolByMainID(list.get(0).getiD());
                returnMap.put("sVCServiceRequestToolVO", toolList);

                // 获取项目性质列表  去掉尊享悦享
                List<SVCItemKindSHVO> ItemKindlist =
                        GetItemKindList(
                                list.get(0).getvSvcKind(),
                                "D49F66C6-52A2-4D87-B5DC-C0698E2A8E74",
                                list.get(0).getcFreeMaintain() + "",
                                list.get(0).getcExtraMaintain() + "");

                returnMap.put("sVCItemKindSHVO", ItemKindlist);

                // 结算
                DbUnionCommonDto sVCSettlementView = new DbUnionCommonDto();
                sVCSettlementView.setQueryConditions("a.NCorID", 0, list.get(0).getiD());
                sVCSettlementView.setQueryConditions("a.CCancel", 0, "1");
                sVCSettlementView.setQueryConditions("a.ndid", 0, userInfor.getnDID());
                List<Svc0104SVCSettlementClubDTO> sVCSettlementList =
                        svc0104SvcOrderMapper.sVCSettlementVO(sVCSettlementView);

                if (sVCSettlementList != null && sVCSettlementList.size() > 0) {
                    returnMap.put("isCancelSettle", "1");
                } else {
                    returnMap.put("isCancelSettle", "0");
                }

                String padnstdID = list.get(0).getnStdID();
                //获取工时定额给pad
                if (StringUtils.isNullOrEmpty(padnstdID)) {

                    // 获取默认工时定额
                    GetStdDTO serviceResult = pucCommonService.GetStdBySaleTypeID(list.get(0).getnSaleTypeID());
                    String stdId = serviceResult.getnStdID();
                    if (!StringUtils.isNullOrEmpty(stdId)) {
                        padnstdID = stdId;
                    }

                }
                if (!StringUtils.isNullOrEmpty(padnstdID)) {
                    SvcStandardrationPO SVCStandardration = new SvcStandardrationPO();
                    SVCStandardration = getnstdID(list.get(0).getnStdID());
                    returnMap.put("pADnstd", SVCStandardration);
                }


            }
            ClmFdbillPO clmpo = new ClmFdbillPO();
            QueryWrapper<ClmFdbillPO> clmqueryWrapper = new QueryWrapper<>();
            clmqueryWrapper.eq("NSvcBillID", sVCGetServiceRequest.getiD());
            clmqueryWrapper.eq("CNew", "1");
            clmqueryWrapper.eq("CDelete", "0");
            List<ClmFdbillPO> clmlist = clmpo.selectList(clmqueryWrapper);
            if (clmlist != null && clmlist.size() > 0) {
                DTSSstutes = "1";
            } else {
                DTSSstutes = "0";
            }

        } else {
            returnMap.put("sVCServiceRequestVO", sVCGetServiceRequest);
        }

        // 删除维修项目权限 前端判断

//        CheckUserRightVO vo = new CheckUserRightVO();
//        vo.setNdid(userInfor.getnDID());
//        vo.setUserID(userInfor.getiD());
//        vo.setvRight("DeleteSvcItem");
//        Map<String, Object> str = iInvokeService.checkuserright(userInfor.getnDID(), vo);
//        Map<String, String> map = (Map<String, String>) str.get("data");
//        Integer returnData = Integer.parseInt(map.get("isEXCE"));
//        if (returnData == 0) {
//            returnMap.put("deleteSvcItem", "0");
//        } else {
//            returnMap.put("deleteSvcItem", "1");
//        }
        // 必须输入首保卡号 取数据字典
//        String MustInputFirstMtNO =
//                stmCommonService.GetParameters("MustInputFirstMtNO", userInfor.getnDID(), "SVC"); // 首保卡号参数
//        returnMap.put("mustInputFirstMtNO", MustInputFirstMtNO);

        // 工时和工时费 允许负数
        String isAllowed = stmCommonService.GetParameters("IsAllowMinus", userInfor.getnBID(), "SVC");
        returnMap.put("isAllowed", isAllowed);

        // DTSS 未上传 不允许打印
//        String LFDSCJSL = stmCommonService.GetParameters("LFDSCJSL", userInfor.getnBID(), "SVC");
        returnMap.put("lFDSCJSL", "0");

        returnMap.put("dTSSstutes", DTSSstutes);
        // 取得取送车服务
//        String takeCarService =
//                stmCommonService.GetParameters("TakeCarService", userInfor.getnBID(), "SVC");
//        returnMap.put("takeCarService", takeCarService);

        //进厂处理自动打印召回书
        /**************panghai 20210621 此参数隐藏，默认0************************************/
//        String LDYZHS =
//                stmCommonService.GetParameters("LDYZHS", userInfor.getnBID(), "SVC");
        returnMap.put("lDYZHS", "0");
        /**************panghai 20210621 此参数隐藏，默认0************************************/

        // 原厂仓库
        SpaWareHouseBePO spaWareHouseBePO = new SpaWareHouseBePO();
        QueryWrapper<SpaWareHouseBePO> spaWareHouseBePOQueryWrapper = new QueryWrapper<>();
        spaWareHouseBePOQueryWrapper.eq("ndid",userInfor.getnDID());
        spaWareHouseBePOQueryWrapper.eq("cMfr","1");
        spaWareHouseBePOQueryWrapper.eq("vWHType","SPA");
        spaWareHouseBePOQueryWrapper.ne("cstop","1");
        List<SpaWareHouseBePO> wareHouseBePOList = spaWareHouseBePO.selectList(spaWareHouseBePOQueryWrapper);
        if(!wareHouseBePOList.isEmpty()){
            List<Map<String,String>> vWHList = new ArrayList<>();
            for (SpaWareHouseBePO item:wareHouseBePOList
            ) {
                Map<String,String> mapWH = new HashMap<>();
                mapWH.put("value",item.getvWH());
                mapWH.put("text",item.getvWHName());
                vWHList.add(mapWH);
            }
            returnMap.put("vWHList", vWHList);
        }

        // 查询维修类型字典
        returnMap.put("svcKindSH",sany0007Mapper.getDistinctSvcKind());

        return returnMap;
    }

    @Override
    public Map<String, Object> getReportInfos(Map<String, String> params) {
        Map<String, Object> map = new HashMap<>();
        //获取用户信息
        DMSLoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        String vParaValue = stmCommonService.GetParameters("LTJQZ", loginInfoDto.getnBID(), "SVC");
        map.putAll(svc0101Mapper.getReportInfosNum(loginInfoDto.getnDID(), params.get("begin"), params.get("end"), vParaValue));
        map.put("repairItems", svc0101Mapper.getRepairItems(loginInfoDto.getnDID(), params.get("begin"), params.get("end"), vParaValue));
        map.put("bookingStatistics", svc0101Mapper.getBookingStatistics(loginInfoDto.getnDID(), params.get("begin"), params.get("end")));
        return map;
    }

    @Override
    public VehiclePO getVehiclePOByID(Map<String, String> params) {
        DMSLoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        VehiclePO vehiclePO = new VehiclePO();
        QueryWrapper<VehiclePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vVin",params.get("vVin"));
        queryWrapper.eq("nDID",loginInfoDto.getnDID());
        queryWrapper.ne("cStop","1");
        List<VehiclePO> vehiclePOS = vehiclePO.selectList(queryWrapper);
        if(vehiclePOS.isEmpty()){
            return null;
        }else{
            return vehiclePOS.get(0);
        }
    }

    @Override
    public List<Map> getVSpaStk(List<String> vSpas) {
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("stk.ndid",0,userInfo.getnDID());
        dbUnionCommonDto.setQueryConditions("stk.vspa",8 ,vSpas);
        List<Map> result = this.svc0101Mapper.getVSpaStk(dbUnionCommonDto);
        logger.info("--------------------------------------------------------");
        logger.info(result.toString());
        return result;
    }

    @Override
    public Message saveOrderImgPath(Svc0101UploadImgVO svc0101UploadImgVO) {
        DMSLoginInfoDto userInfor = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        String iD = svc0101UploadImgVO.getiD();
        List<String> vPaths = svc0101UploadImgVO.getvPaths();
        //查委托书服务订单号
        SvcOrderPO svcOrderPO = new SvcOrderPO();
        svcOrderPO = svcOrderPO.selectById(iD);
        for (String item:vPaths
             ) {
            SvcOrderFilePO svcOrderFilePO = new SvcOrderFilePO();
            svcOrderFilePO.setiD(UUID.randomUUID().toString());
            svcOrderFilePO.setnMainID(iD);
            svcOrderFilePO.setvPath(item);
            svcOrderFilePO.setvTransCode("SVC0101");
            svcOrderFilePO.setcDelete("0");
            /****************20220930 逄海 微信上传图片自动编写图片名称******************************/
            String VImgName = this.getVIMGName(userInfor.getnDID(),iD,svcOrderPO.getvBillNO(),svc0101UploadImgVO.getvType());
            svcOrderFilePO.setvName(VImgName);
            /****************20220930 逄海 微信上传图片自动编写图片名称******************************/
            svcOrderFilePO.setvType(svc0101UploadImgVO.getvType());


            //给CRM传图片
            Map<String,String> fileMap = new HashMap<>();
            fileMap.put("IV_GUID","");//代理商编号
            fileMap.put("IV_OBJECT_ID",svcOrderPO.getvObjectID().split(";")[0]);//服务订单
            if ("00".equals(svc0101UploadImgVO.getvType())){
                fileMap.put("ZZATTCH_TYPE","005");//维修前故障图片
            }else{
                fileMap.put("ZZATTCH_TYPE","004");//维修后故障图片
            }

            fileMap.put("ZZATTACH_NAME",svcOrderFilePO.getvName());//名称
            fileMap.put("ZZCONTENT_URL",svcOrderFilePO.getvPath());//URL
            fileMap.put("ZZFTPFNAME",svcOrderFilePO.getFtpName());//附件FTP文件名
            fileMap.put("ZZFILE_EXT","");//字符串
            fileMap.put("ZZFILE_SIZE","");//文件大小（按字节）
            fileMap.put("ZZCREATED_BY",userInfor.getvPersonName());//创建者
            fileMap.put("ZZCREATED_ON",LocalDateTimeUtils.localDateTimeToString(LocalDateTime.now(),"yyyyMMdd"));//创建时间（用户时区中的输出）
            fileMap.put("OBJECT_ID","");//处理标识
            fileMap.put("GUID","");//字符字段，长度 32 插入不填；更新、删除 必填
            fileMap.put("MODE","I");//变更模式 I：插入，U：更新，D：删除
            logger.info("上传附件参数"+fileMap);
            String guid = this.svcToSanyCrmService.upLoadFile(fileMap);
            svcOrderFilePO.setGuid(guid);
            svcOrderFilePO.insert();
        }
        message.putMessage("SREMessage", "112");
        return message;
    }

    @Override
    public List<SvcOrderFilePO> getOrderImgPath(Svc0101UploadImgVO svc0101UploadImgVO) {
        List<SvcOrderFilePO> svcOrderFilePOS = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(svc0101UploadImgVO.getiD())){
            //添加委托书图片显示
            SvcOrderFilePO svcOrderFilePO = new SvcOrderFilePO();
            QueryWrapper<SvcOrderFilePO> svcOrderFilePOQueryWrapper = new QueryWrapper<>();
            svcOrderFilePOQueryWrapper.eq("nMainID",svc0101UploadImgVO.getiD());
            svcOrderFilePOQueryWrapper.ne("cDelete","1");
            svcOrderFilePOQueryWrapper.eq("vTransCode","SVC0101");
            svcOrderFilePOQueryWrapper.eq("vType",svc0101UploadImgVO.getvType());
            svcOrderFilePOS = svcOrderFilePO.selectList(svcOrderFilePOQueryWrapper);
        }else{
            message.putMessage("SVCMessage","125",new String[]{"未找到对应委托书，请关闭页面重新操作"});
        }

        return svcOrderFilePOS;
    }

    @Override
    public List<Map> getGuestBoard() {
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        List<Map> result = this.svc0101Mapper.getGuestBoard(userInfo.getnDID());
        return result;
    }

    @Override
    public List<SVCGetServiceRequest> getMergePrint(SVCGetServiceRequest svcGetServiceRequest) {
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("r.vcusname",6,svcGetServiceRequest.getvCusName());
        dbUnionCommonDto.setQueryConditions("a.vvin",6,svcGetServiceRequest.getvVin());
        dbUnionCommonDto.setQueryConditions("a.ndid",6,userInfo.getnDID());
        dbUnionCommonDto.setQueryConditions("a.nbid",6,userInfo.getnBID());
        List<SVCGetServiceRequest> result = this.svc0101Mapper.getMergePrint(dbUnionCommonDto);
        return result;
    }

    @Override
    public Map getMergePrintInfo(List<String> ids) {
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        DbUnionCommonDto dbUnionCommonDto = new DbUnionCommonDto();
        dbUnionCommonDto.setQueryConditions("a.id",8,ids);
        //取得客户信息
        Map cusInfo = this.svc0101Mapper.getMergePrintCusInfo(dbUnionCommonDto);
        //取得车辆信息
        List<Map> vinInfo = this.svc0101Mapper.getMergePrintVINInfo(dbUnionCommonDto);
        //取得项目信息
        List<Map> itemInfo = this.svc0101Mapper.getMergePrintItemInfo(dbUnionCommonDto);
        List<Map> itemTotalInfo = this.svc0101Mapper.getMergePrintItemTotalInfo(dbUnionCommonDto);
        //取得配件信息
        List<Map> spaInfo = this.svc0101Mapper.getMergePrintSpaInfo(dbUnionCommonDto);
        List<Map> spaTotalInfo = this.svc0101Mapper.getMergePrintSpaTotalInfo(dbUnionCommonDto);
        //取得其他费用数据
        Map otherFeeInfo = this.svc0101Mapper.getMergePrintOtherFeeInfo(dbUnionCommonDto);
        String v_Director = this.stmCommonService.GetParameters("CFWZJ",userInfo.getnBID(),"SYS");
        String v_Address = this.stmCommonService.GetParameters("CDZ",userInfo.getnBID(),"SYS");
        String v_Tel = this.stmCommonService.GetParameters("CDH",userInfo.getnBID(),"SYS");
        //取得经销商名称
        DbUnionCommonDto dbUnionCommonDto1 = new DbUnionCommonDto();
        dbUnionCommonDto1.setQueryConditions("id",0,userInfo.getnBID());
        String v_VDealerName = this.svc0101Mapper.getVDealerName(dbUnionCommonDto1);
        Map result = new HashMap();
        result.put("cusInfo",cusInfo);
        result.put("vinInfo",vinInfo);
        result.put("itemInfo",itemInfo);
        result.put("itemTotalInfo",itemTotalInfo);
        result.put("spaInfo",spaInfo);
        result.put("spaTotalInfo",spaTotalInfo);
        result.put("v_Director",v_Director);
        result.put("v_Address",v_Address);
        result.put("v_Tel",v_Tel);
        result.put("v_VDealerName",v_VDealerName);
        result.put("otherFeeInfo",otherFeeInfo);
        return result;
    }

    @Override
    public Message upLoadObjectIDStatus(String id,String code) {
        svcToSanyCrmService.upLoadObjectIDCode(id,code);
        SvcOrderPO svcOrderPO = new SvcOrderPO();
        svcOrderPO = svcOrderPO.selectById(id);
        if ("B".equals(code)){
            svcOrderPO.setcCompensate(1);
        }else if ("C2".equals(code)){
            svcOrderPO.setcCompensate(2);
        }else{
            svcOrderPO.setcCompensate(0);
        }

        svcOrderPO.updateById();
        message.putMessage("SREMessage", "009");
        return message;
    }

    /**
     * 销售订单详情接口
     */
    private Map viewSaleOrderDetails(String IV_OBJECT_ID){
        Map result = new HashMap();
        Map data = this.svcToSanyCrmService.viewSaleOrderDetails(IV_OBJECT_ID);
        //取得销售订单数据
        List<Map> saleOrderInfo = (List<Map>)data.get("ET_OUTPUT");
        if (saleOrderInfo != null && !saleOrderInfo.isEmpty()){
            String pmnttrms = saleOrderInfo.get(0).get("PMNTTRMS") == null ? "":saleOrderInfo.get(0).get("PMNTTRMS").toString();//支付条款
            String zzlgorth = saleOrderInfo.get(0).get("ZZLGORTH") == null ? "":saleOrderInfo.get(0).get("ZZLGORTH").toString();//支付条款
            result.put("pmnttrms",pmnttrms);
            result.put("zzlgorth",zzlgorth);
        }

        //取得配件信息
        List<SanyCrmSpaDTO> spas = new ArrayList<>();
        List<Map> spasInfo = (List<Map>)data.get("ET_ITEM");
        if (spasInfo != null && !spasInfo.isEmpty()){
            for (Map item:spasInfo
            ) {
                SanyCrmSpaDTO sanyCrmSpaDTO = new SanyCrmSpaDTO();
                sanyCrmSpaDTO.setvSpa(item.get("PRODUCT_ID").toString());
                sanyCrmSpaDTO.setvSpaAlias(item.get("DESCRIPTION").toString());
                sanyCrmSpaDTO.setnQty(new Double(item.get("QTY").toString()));
                sanyCrmSpaDTO.setnPrice(new Double(item.get("PRICE").toString()));
                spas.add(sanyCrmSpaDTO);
            }
            //根据配件代码分组，重新计算配件数量和金额
            Map<String, List<SanyCrmSpaDTO>> group =spas.stream().collect(Collectors.groupingBy(SanyCrmSpaDTO::getvSpa));
            logger.info("---------------------------------------------------");
            logger.info(group.toString());

            List<SvcOrderSpaPO> spalists = new ArrayList<>();
            for (String key:group.keySet()){
                SvcOrderSpaPO svcOrderSpaPO = new SvcOrderSpaPO();
                DoubleSummaryStatistics doubleSummaryStatistics= group.get(key).stream().collect(Collectors.summarizingDouble(SanyCrmSpaDTO::getnQty));
                Double nQtySum = doubleSummaryStatistics.getSum();
                svcOrderSpaPO.setvSpa(key);
                svcOrderSpaPO.setvSpaAlias(group.get(key).get(0).getvSpaAlias());
                svcOrderSpaPO.setnQty(new BigDecimal(nQtySum));
                svcOrderSpaPO.setnPrice(new BigDecimal(group.get(key).get(0).getnPrice()));
                spalists.add(svcOrderSpaPO);
            }
            result.put("spalists",spalists);
        }

        return result;
    }


        /**
         * 服务订单详情接口
         */
        private Map viewServiceOrderDetails(String IV_OBJECT_ID){
            Map result = new HashMap();
            Map data = this.svcToSanyCrmService.viewServiceOrderDetails(IV_OBJECT_ID);

            //取得配件信息
            List<SanyCrmSpaDTO> spas = new ArrayList<>();
            List<Map> spasInfo = (List<Map>)data.get("ET_ITEM");
            if (spasInfo != null && !spasInfo.isEmpty()){
                for (Map item:spasInfo
                ) {
                    SanyCrmSpaDTO sanyCrmSpaDTO = new SanyCrmSpaDTO();
                    sanyCrmSpaDTO.setvSpa(item.get("PRODUCT_ID").toString());
                    sanyCrmSpaDTO.setvSpaAlias(item.get("DESCRIPTION").toString());
                    sanyCrmSpaDTO.setnQty(new Double(item.get("QTY") == null ?"0":item.get("QTY").toString()));
                    sanyCrmSpaDTO.setnPrice(new Double(item.get("PRICE") == null ?"0":item.get("PRICE").toString()));
                    sanyCrmSpaDTO.setvWH(item.get("ZZLGORTH") == null ?"":item.get("ZZLGORTH").toString());
                    spas.add(sanyCrmSpaDTO);
                }
                //根据配件代码分组，重新计算配件数量和金额
                Map<String, List<SanyCrmSpaDTO>> group =spas.stream().collect(Collectors.groupingBy(SanyCrmSpaDTO::getvSpa));
                logger.info("---------------------------------------------------");
                logger.info(group.toString());

                List<SvcOrderSpaPO> spalists = new ArrayList<>();
                for (String key:group.keySet()){
                    SvcOrderSpaPO svcOrderSpaPO = new SvcOrderSpaPO();
                    DoubleSummaryStatistics doubleSummaryStatistics= group.get(key).stream().collect(Collectors.summarizingDouble(SanyCrmSpaDTO::getnQty));
                    Double nQtySum = doubleSummaryStatistics.getSum();
                    svcOrderSpaPO.setvSpa(key);
                    svcOrderSpaPO.setvSpaAlias(group.get(key).get(0).getvSpaAlias());
                    svcOrderSpaPO.setnQty(new BigDecimal(nQtySum));
                    svcOrderSpaPO.setnPrice(new BigDecimal(group.get(key).get(0).getnPrice()));
                    svcOrderSpaPO.setvWH(group.get(key).get(0).getvWH());
                    spalists.add(svcOrderSpaPO);
                }
                result.put("spalists",spalists);
            }


        return result;
    }

    private  void updateSpaByCrmServiceOrder(String iD,List<SvcOrderSpaPO> crmSpalists){

        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        //每次获取销售订单后全量更新配件信息
        SvcOrderSpaPO svcOrderSpaPO = new SvcOrderSpaPO();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("nMainid",iD);
        queryWrapper.in("vChannel",Arrays.asList("1","01"));
        List<SvcOrderSpaPO> spas = svcOrderSpaPO.selectList(queryWrapper);
        Map<String, List<SvcOrderSpaPO>> group =spas.stream().collect(Collectors.groupingBy(SvcOrderSpaPO::getvSpa));
        //正向对比，查出上游的件和本地件不同的，说明在上游做了修改。此时按上游数据修改本地数据
        if (crmSpalists==null){
            crmSpalists = new ArrayList<SvcOrderSpaPO>();
        }
        for (SvcOrderSpaPO spa:crmSpalists
        ) {
            String vSpa = spa.getvSpa();
            //目前配件种类包含上游配件，对比数量,相同不做处理，不相同修改数量
            if (group.containsKey(vSpa)){
                BigDecimal nQty = group.get(vSpa).get(0).getnQty();
                if (nQty.compareTo(spa.getnQty()) != 0){
                    //修改预估配件数量
                    group.get(vSpa).get(0).setnQty(spa.getnQty());
                    //修改已经上传的数量
                    SvcUploadCrmSpaPO svcUploadCrmSpaPO = new SvcUploadCrmSpaPO();
                    QueryWrapper<SvcUploadCrmSpaPO> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("nMainid",group.get(vSpa).get(0).getnMainID());
                    queryWrapper1.eq("vSpa",group.get(vSpa).get(0).getvSpa());
                    queryWrapper1.eq("ndid",group.get(vSpa).get(0).getnDID());
                    svcUploadCrmSpaPO = svcUploadCrmSpaPO.selectOne(queryWrapper1);
                    svcUploadCrmSpaPO.setnQty(spa.getnQty());
                    svcUploadCrmSpaPO.updateById();

                    //同时修改预估配件数量
                    QueryWrapper<SvcOrderSpaPO> svcOrderSpaPOQueryWrapper = new QueryWrapper<>();
                    svcOrderSpaPOQueryWrapper.eq("nmainid",iD);
                    svcOrderSpaPOQueryWrapper.eq("vspa",vSpa);
                    SvcOrderSpaPO updataPO = spa.selectOne(svcOrderSpaPOQueryWrapper);
                    updataPO.setnQty(spa.getnQty());
                    updataPO.updateById();
                }
            }
            //目前配件种类不包含上游配件，预估配件插入新种类配件
            else{
                SvcUploadCrmSpaPO svcUploadCrmSpaPOAdd = new SvcUploadCrmSpaPO();
                svcUploadCrmSpaPOAdd.setvSpa(spa.getvSpa());
                svcUploadCrmSpaPOAdd.setnMainID(iD);
                svcUploadCrmSpaPOAdd.setnQty(spa.getnQty());
                svcUploadCrmSpaPOAdd.setnDID(userInfo.getnDID());
                svcUploadCrmSpaPOAdd.insert();

//                SvcOrderSpaPO insertPO = new SvcOrderSpaPO();
                spa.setnMainID(iD);
                spa.setvModule("SPA");
//                spa.setvWH(spa.getvWH());
                spa.setvChannel("1");
                spa.setvKind("2");
                spa.setnDID(userInfo.getnDID());
                spa.insert();
            }
        }

        //反向对比，找出本地存在上游没有的，说明上游已经删除了，此时删除预估配件和记录表数据
        Map<String, List<SvcOrderSpaPO>> groupCrm =crmSpalists.stream().collect(Collectors.groupingBy(SvcOrderSpaPO::getvSpa));
        for (SvcOrderSpaPO spa:spas
        ) {
            String vSpa = spa.getvSpa();
            //目前配件种类包含上游配件，对比数量,相同不做处理，不相同修改数量
            if (!groupCrm.containsKey(vSpa)){
                //修改已经上传的数量
                SvcUploadCrmSpaPO svcUploadCrmSpaPO = new SvcUploadCrmSpaPO();
                QueryWrapper<SvcUploadCrmSpaPO> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("nMainid",group.get(vSpa).get(0).getnMainID());
                queryWrapper2.eq("vSpa",group.get(vSpa).get(0).getvSpa());
                queryWrapper2.eq("ndid",group.get(vSpa).get(0).getnDID());
                svcUploadCrmSpaPO = svcUploadCrmSpaPO.selectOne(queryWrapper2);
                svcUploadCrmSpaPO.deleteById();

                spa.deleteById();
            }
        }



    }

    private  void updateSpaByCrmSaleOrder(String iD,String vWH,List<SvcOrderSpaPO> crmSpalists){
        DMSLoginInfoDto userInfo = ApplicationContextHelper.getBeanByType(DMSLoginInfoDto.class);
        //每次获取销售订单后全量更新配件信息
        SvcOrderSpaPO svcOrderSpaPO = new SvcOrderSpaPO();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("nMainid",iD);
        queryWrapper.in("vChannel",Arrays.asList("1","01"));
        logger.info("-------------------------------------------------");
        logger.info("删除原有销售订单配件数据");
        svcOrderSpaPO.delete(queryWrapper);

        //新增配件信息
        logger.info("+++++++++++++++++++++++++++++++++++++++++");
        logger.info("新增实时销售订单数据");
        if (crmSpalists != null && !crmSpalists.isEmpty()){
            for (SvcOrderSpaPO item:crmSpalists
            ) {
                item.setnMainID(iD);
                item.setvModule("SPA");
                item.setvWH(vWH);
                item.setvChannel("1");
                item.setvKind("2");
                item.setnDID(userInfo.getnDID());

                item.insert();
            }
        }

    }

    private void modifySaleOrder(String vObjectID,List<SVCServiceRequestSpaDTO> svcServiceRequestSpaDTOS){
        //委托书信息
        SVCSaleOrderInfoDTO svcSaleOrderInfoDTO = new SVCSaleOrderInfoDTO();
        svcSaleOrderInfoDTO.setiVOBJECTID(vObjectID);


        Map mapOrder = new HashMap();
        mapOrder.put("spas",svcServiceRequestSpaDTOS);
        mapOrder.put("svcSaleOrderInfoDTO",svcSaleOrderInfoDTO);

        this.svcToSanyCrmService.modifySaleOrder(mapOrder);
    }

    /**
     *
     * @param nDID
     * @param nMainId
     * @param vBillNo
     * * @param vType
     * @return VIMGName 图片名称
     */
    private String getVIMGName(String nDID,String nMainId,String vBillNo,String vType){
        DbUnionCommonDto db = new DbUnionCommonDto();
        db.setQueryConditions("a.ndid",0,nDID);
        db.setQueryConditions("a.nMainid",0,nMainId);
        db.setQueryConditions("a.cDelete",0,"0");
        db.setQueryConditions("a.vType",0,vType);
        String VIMGNO = svc0101Mapper.VIMGNO(db);
        if (VIMGNO != null && !VIMGNO.isEmpty()) {
            int IMGNO = Integer.parseInt(VIMGNO) + 1;
            VIMGNO = String.format( "%06d", IMGNO);
        }else{
            VIMGNO = "000001";
        }
        String vTypeName = "";
        if (("00").equals(vType)){
            vTypeName = "维修前";
        }else if (("01").equals(vType)){
            vTypeName = "维修后";
        }

        String VImgName= vBillNo + "-" + vTypeName + "-" + VIMGNO;

        return VImgName;
    }

}
